// uva 699 - The Falling Leaves
// 题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=104&page=show_problem&problem=640
// 题目大意:给出一棵二叉树先序遍历的结果,-1表示节点为空,每个节点垂直往下落叶,落叶的数量为节点的值,也就是5和6是落在一个点上的,落在这个点上的值为11。求个点上的落叶数
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int cnt_case;
struct Node{
int val;
int pos;
Node *left, *right;
}*root;
const int MAXN = 10000;
int min_pos;
int leaves_number[MAXN];
void BuildTree(Node*);
void GetLeaves(Node*);
void Init();
void Release(Node*);
void Print();
int main(){
int tmp_val;
while(scanf("%d", &tmp_val), tmp_val != -1){
Init();
root = new Node();
root->val = tmp_val;
BuildTree(root);
GetLeaves(root);
Print();
Release(root);
}
return 0;
}
void Init(){
memset(leaves_number, 0, sizeof(leaves_number));
min_pos = 0;
}
void Release(Node* root){
if(root->left)
Release(root->left);
if(root->right)
Release(root->right);
delete root;
}
void BuildTree(Node* root){
int tmp_val;
scanf("%d", &tmp_val);
if(tmp_val != -1){
root->left = new Node();
root->left->val = tmp_val;
root->left->pos = root->pos - 1;
if(min_pos > root->left->pos)
min_pos = root->left->pos;
BuildTree(root->left);
}
scanf("%d", &tmp_val);
if(tmp_val != -1){
root->right = new Node();
root->right->val = tmp_val;
root->right->pos = root->pos + 1;
if(min_pos > root->right->pos)
min_pos = root->right->pos;
BuildTree(root->right);
}
}
void GetLeaves(Node* root){
leaves_number[root->pos - min_pos] += root->val;
if(root->left)
GetLeaves(root->left);
if(root->right)
GetLeaves(root->right);
}
void Print(){
cout << "Case " << ++cnt_case << ":" << endl;
for(int i = 0; leaves_number[i] != 0; i++){
if(i)
cout << " ";
cout << leaves_number[i];
}
cout << endl << endl;
}
uva 699 - The Falling Leaves
最新推荐文章于 2023-11-24 11:35:07 发布