poj2255Tree Recovery

数据结构应该有讲,前序遍历和中序遍历 或者是中序遍历和后序遍历可以恢复整个二叉树,然后在建立利用另一种遍历

14272030h1231202255Accepted688K0MSG++1278B2015-06-06 17:18:47
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
#include<memory>
using namespace std;
const int maxn=10000+100;
char pre_order[maxn], in_order[maxn],lch[maxn],rch[maxn];
int build(int L1,int R1,int L2,int R2)//把pre_order和in_order
{
        if(L2>R2) return 0;//空树
        int root=pre_order[L1];//前序遍历的最前边的字符总是根结点
        int p=L2;
        while(in_order[p]!=root)  p++;//找到根结点的编号
        int cnt=p-L2;//找到左子树的长度
      //  cout<< L1+1<<" "<<L1+cnt+1<<" "<<L2<<" "<<p-1;
        lch[root]=build(L1+1,L1+cnt,L2,p-1);
        //cout<<L1+cnt+2<<" "<<R1<<" "<<p+1<<" "<<R2;
        rch[root]=build(L1+cnt+1,R1,p+1,R2);
        return root;
}
int  postorder_traversal(int u)//后序遍历
{
        if(u)
        {
                postorder_traversal(lch[u]);
                 postorder_traversal(rch[u]);
                 printf("%c",u);
        }
}
int main()
{
         while(scanf("%s%s",pre_order,in_order)!=EOF)
        {
                       memset(lch,0,sizeof(lch));
                       memset(rch,0,sizeof(rch));//为0的当成空节点
                      build(0,strlen(pre_order)-1,0,strlen(in_order)-1);//建树
                      postorder_traversal(pre_order[0]);//后序遍历
                      printf("\n");
        }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值