UVA 699 The Falling Leaves
题意 输入一棵树,把垂直方向上同一位置的叶子节点值加以来,最后逐个输出
思路 题目中是按前序输入树,所以就按前序来建立一棵树,之后建一个数组,从数组中间开始存,每次访问左节点就把数组往左存,访问右节点就往右,最后输出储存的数组即可
代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int num[1000];
int output[1000];
typedef struct node
{
int t;
int data;
struct node *rchild;
struct node *lchild;
} BTNode;
BTNode *create(int tt)
{
BTNode *root;
int ro;
scanf("%d",&ro);
if(ro == -1)
root = NULL;
else
{
num[tt] += ro;
root = (BTNode *)malloc(sizeof(BTNode));
root -> data = ro;
root -> lchild=create(tt - 1);
root -> rchild=create(tt + 1);
}
return root;
}
int main()
{
int ttt = 1;
while (1)
{
BTNode *t;
int j = 0;
memset(num, 0, sizeof(num));
t = create(500);
if (t == NULL)
break;
for (int i = 0 ; i < 1000; i ++)
{
if (num[i])
output[j++] = num[i];
}
printf("Case %d:\n", ttt ++);
for (int i = 0; i < j - 1; i ++)
printf("%d ", output[i]);
printf ("%d\n", output[j - 1]);
printf("\n");
}
return 0;
}