紫书章六例题10 下落的树叶 UVA 699 (根据前序遍历建树)

这个题卡了蛮久。然后改过来后,发现题目意思和自己想的出了一点问题。本以为是一行是一颗树,然后题目中并没有说。所以可能好几行是一棵树。所以用了边读边建树。因为前面的那道题是有明显的标识,如果W1=0 ,建左子树,如果W2=0,建右子树。而且到了叶子节点后不用考虑其他的。但是这道题,之前的不能判断之后是不是叶子,所以。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <sstream>
#include <cmath>

using namespace std;
struct node
{
    int data;
    node *l,*r;
    node(int a=0,node *left=NULL,node *right=NULL)
    {
        data=a,l=left,r=right;
    }
};
node *root;
int ans[305];
void remove_tree(node *t)
{
    if(t == NULL) return ;
    remove_tree(t->l);
    remove_tree(t->r);
    delete t;
}
int now=1,h;
int qx;
node *buildtree(node *t,int ht)
{
    scanf("%d",&qx);
    if(qx!=-1)  {
        if(t->l==NULL) t->l=new node();
        t->l->data=qx;ans[ht-1]+=qx;
        buildtree(t->l,ht-1);
    }
   if(qx==-1) scanf("%d",&qx);//这里
    if(qx!=-1) {
        if(t->r==NULL) t->r = new node();
        t->r->data=qx;ans[ht+1]+=qx;
        buildtree(t->r,ht+1);
    }
}

int main()
{
    //freopen("E:\\input.txt","r",stdin);
    int g;
    int case1=0;
    while(scanf("%d",&g))
    {
        if(g==-1) break;
        memset(ans,0,sizeof(ans));
        remove_tree(root);
        root=new node();
        h=0;
        root->data=g;
        ans[160]=g;
        buildtree(root,160);
        int flag=0,num=0;
       // if(case1) printf("\n");
        printf("Case %d:\n",++case1);
        for(int i=70;i<300;i++)
        {
            if(ans[i]) {if(flag) printf(" ");printf("%d",ans[i]);num++;flag=1;}
        }
        printf("\n\n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值