699 - The Falling Leaves

题目:699 - The Falling Leaves


题目大意:给一棵树,要求算在同一竖直位置的值得和,从左到右打印出来;

解题思路:先建树,然后重点就是调用递归来将同一竖直位置的值加起来,用一个数组来存放,根放在数组最中间,左边的孩子就中间-1,右边的就中间的加1,这样同一竖直的位置的就会加到相同的数组元素里,并且要同时记录最左边的数,以便后面输出时控制最后的回车。


#include<stdio.h>
#include<string.h>

const int N =  10000;
int s[N], m;

struct tree {

	int d; 
	tree *left, *right;
	tree(int a) { d = a; left = right = NULL;}
} *head;

void buildtree(tree *&p, int a) {
	
	p = new tree(a);
	scanf("%d", &a);
	if(a != -1)
		buildtree(p->left, a);
	scanf("%d", &a);
	if(a != -1)
		buildtree(p->right, a);

}

void clear(tree *&p) {

	if(p != NULL) {

		clear(p->left);
		clear(p->right);
		delete(p);
		p = NULL;
	}
}

void handle (tree *p, int k) {

	if(p != NULL) {
		
 		s[k] += p->d;
		if(m < k)
			m = k;
		handle(p->left, k -1);
		handle(p->right, k + 1);
		
	}
}


int main() {
	
	int x, n = 0;
	while(scanf("%d", &x) && x != -1) {

		n++;
		m = 0;
		printf("Case %d:\n", n);
		buildtree(head, x);
		memset(s, 0, sizeof(s));
		handle(head, N/2);
		for(int i = 0; i <= m; i++)
			if(s[i]) {
					if(i != m)
						printf("%d ",s[i]);
					else
						printf("%d\n\n", s[i]);
			}
		clear(head);
	}
	return 0;
}


你可能感兴趣的:(699 - The Falling Leaves)