UVA 699 The Falling Leaves (递归先序建立二叉树)

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

题目链接:http://acm.hust.edu.cn/vjudge/problem/19244

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <climits>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <vector>
#include <list>
#include<functional>
#define mod 1000000007
#define inf 0x3f3f3f3f
#define pi acos(-1.0)
using namespace std;
typedef long long ll;
const int N=;
const int maxn = ;
int sum[maxn];
// 输入并统计一棵子树,树根水平位置为p
void build(int p) {
int v;
cin >> v;
if(v == -) return; // 空树
sum[p] += v;
build(p - );
build(p + );
}
// 边读入边统计
bool init() {
int v;
cin >> v;
if(v == -) return false;
memset(sum, , sizeof(sum));
int pos = maxn/; // 树根的水平位置
sum[pos] = v;
build(pos - ); // 左子树
build(pos + ); // 右子树
return true;
}
int main() {
int kase = ;
while(init()) {
int p = ;
while(sum[p] == ) p++; // 找最左边的叶子
// 开始输出。因为要避免行末多余空格,所以稍微麻烦一点
cout << "Case " << ++kase << ":\n" << sum[p++];
while(sum[p] != ) {
cout << " " << sum[p];
p++;
}
cout << "\n\n";
}
return ;
}