poj2255Tree Recovery

来源:互联网 发布:网络用语棒子什么意思 编辑:程序博客网 时间:2024/06/15 03:20

数据结构应该有讲,前序遍历和中序遍历 或者是中序遍历和后序遍历可以恢复整个二叉树,然后在建立利用另一种遍历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
原创粉丝点击