UVA

#include <iostream>
#include <cstring>
using namespace std;
const int maxn = 100;
int sum[maxn];

//输入并统计一颗子树,树根水平位置为 p 
void build (int p)
{
	int v;
	cin >> v;
	if (v == -1) return; //空树 
	sum[p] += v;
	build(p - 1);
	build(p + 1);
}

bool init()
{
	int v;
	cin >> v;
	if (v == -1) return false; //先序遍历输入,第一个数据就是树根,如果第一个数据为 -1,说明整个树都为空 
	memset(sum, 0, sizeof(sum));
	int pos  = maxn / 2;
	sum[pos] = v;
	build (pos - 1); 
	build (pos + 1); // biild的参数,为权值累加的位置,在数组中的下标 
	
}

int main()
{
	int kase = 0;
	while (init())
	{
		int p = 0;
		while (sum[p] == 0) p++; //找最左边的叶子
		cout << "Case " << ++kase << ":" << endl << sum[p++]; // 因为要避免行末输出多余的空格
		while (sum[p] != 0) cout << " " << sum[p++];
		cout << endl << endl; //Follow the output for each case by a blank line,注意是 each case!! 
		
	}
	return 0;
}

原文地址:https://www.cnblogs.com/mofushaohua/p/7789399.html