uva 699 - The Falling Leaves

// 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值