Photolog

Through the Looking-Glass
2010-10-12: Through the Looking-Glass
My radio speaks is binary!
2010-10-10: My radio speaks is binary!
Gigaminx: (present for my birthday)
2010-09-16: Gigaminx: (present for my birthday)
Trini on bike
2010-09-05: Trini on bike
Valporquero
2010-08-28: Valporquero
My new bike!
2010-08-22: My new bike!
Mario and Ana's wedding
2010-08-13: Mario and Ana's wedding
Canyoning in Guara
2010-08-07: Canyoning in Guara
Trini and Mari in Marbella
2010-08-05: Trini and Mari in Marbella
Trini and Chelo in Tabarca
2010-08-03: Trini and Chelo in Tabarca
Valid XHTML 1.1
Log in
Back to list of problems

Tree Summing

112.c

/* Tree Summing */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

struct tree {
	int valor;
	struct tree * left;
	struct tree * right;
};

int
sum_tree(int n, struct tree * t)
{
	if (t==NULL) {
		return 0;
	} else if (n==t->valor && !t->left && !t->right) {
		return 1;
	} else {
		return sum_tree(n-(t->valor), t->left) || sum_tree(n-(t->valor), t->right);
	}
}

struct tree *
lee_tree(void)
{
	int a;
	struct tree * result;

	a = getc(stdin);
	while(isspace(a)) {
		a = getc(stdin);
	}
	if (a!='(') {
		printf("error\n");
		return NULL;
	}
	a = getc(stdin);
	while(isspace(a)) {
		a = getc(stdin);
	}
	if (a==')') {
		return NULL;
	}
	ungetc(a, stdin);
	if (scanf("%d", &a)!=1) {
		printf("error\n");
		return NULL;
	}
	result = malloc(sizeof(struct tree));
	result->valor = a;
	result->left = lee_tree();
	result->right = lee_tree();
	a = getc(stdin);
	while(isspace(a)) {
		a = getc(stdin);
	}
	if (a!=')') {
		printf("error\n");
		return NULL;
	}
	return result;
}

int
main(void)
{
	int sum;
	struct tree * my_tree;
	while(1) {
		if (scanf("%d", &sum)!=1) {
			break;
		}
		my_tree = lee_tree();
		if (sum_tree(sum, my_tree)) {
			printf("yes\n");
		} else {
			printf("no\n");
		}
	}
	exit(0);
}