原题链接:https://vjudge.net/problem/UVA-699
分类:树
备注:水题、DFS
思路:该题的关键是对每个节点位置的判断,左儿子位置为父亲位置-1,右儿子位置为父亲位置+1,出现-1值则不管这个儿子,那么可以利用递归的特性来建树。因为数组一般不会考虑有负数的下标,所以这里考虑用map来记录每个位置的值。
代码如下:
#include<cstdio>
#include<map>
using namespace std;
int L, R, kase;
map<int, int>drop;
void Build(int key,int pos)
{
drop[pos] += key;
if (pos < L)L = pos;
if (pos > R)R = pos;
int lson, rson;
scanf("%d", &lson);
if (lson != -1)Build(lson, pos - 1);
scanf("%d", &rson);
if (rson != -1)Build(rson, pos + 1);
}
int main(void)
{
int begin;
while (~scanf("%d",&begin))
{
if (begin == -1)break;
drop.clear();
L = R = 0;
Build(begin, 0);
printf("Case %d:\n",++kase);
for (int i = L; i <= R; i++)
printf("%d%c", drop[i], i == R ? '\n' : ' ');
printf("\n");
}
return 0;
}