uva 699 The Falling Leaves dfs实现

时间:2023-03-08 20:12:07

额,刘汝佳小白里面的配套题目。

题目求二叉树同垂直线上结点值的和。

可以用二叉树做,挺水的其实。

尝试使用dfs实现了:开一个大点的数组,根节点为最中间那点,然后读取时就可以进行和的计算了。

代码:

#include <cstdio>
#include <cstring>
const int maxn = 10000;
int n = 500, tmp, num = 1;
int cnt[maxn] = {0}; bool input(void) {
scanf("%d", &tmp);
if (tmp != -1) {
cnt[n] += tmp;
n--;
input();
n += 2;
input();
n--;
return true;
}
else
return false;
} void output(void) {
int i;
for (i = 0; i <= maxn; i++)
if (cnt[i] != 0)
break;
printf("Case %d:\n%d", num++, cnt[i++]);
for (; i <= maxn; i++)
if (cnt[i] == 0)
break;
else
printf(" %d", cnt[i]);
printf("\n\n");
memset(cnt, 0, sizeof(cnt));
} int main() {
while(input())
output();
return 0;
}