Tree Recovery UVA536

题目大意:给出一个树的先序和中序遍历,让给你构建树,然后输出它的后序遍历

树的结点是由大写字母构成,都不相同。

代码如下:

#include <iostream>
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
const int maxv=30;
char first_order[maxv],middle_order[maxv],s[26];
int l,fir_order[maxv],mid_order[maxv],lch[maxv],rch[maxv];
vector<char> ans;
int build(int L1,int R1,int L2,int R2)
{
    if(L1>R1)
        return -1;
    int root=fir_order[L1];
    int p=L2;
    while(mid_order[p]!=root)
        p++;
    int cnt=p-L2;//左子树的结点个数
    lch[root]=build(L1+1,L1+cnt,L2,p-1);
    rch[root]=build(L1+cnt+1,R1,p+1,R2);
    return root;
}

void  dfs(int u)
{
    if(lch[u] >= 0)
        dfs(lch[u]);
    if(rch[u]>=0)
        dfs(rch[u]);
    ans.push_back(s[u]);
}
int main()
{
   // freopen("in.txt","r",stdin);
    for(int i=0; i<26; i++)
            s[i]='A'+i;
    while(scanf("%s %s",first_order,middle_order)!=EOF)
    {
        ans.clear();
        memset(lch,-1,sizeof(lch));
        memset(rch,-1,sizeof(rch));
        l=strlen(first_order);
        for(int i=0; i<l; i++)
        {
            fir_order[i]=first_order[i]-'A';
            mid_order[i]=middle_order[i]-'A';
        }
        build(0,l-1,0,l-1);
        dfs(fir_order[0]);
        for(int i=0; i<ans.size(); i++)
            printf("%c",ans[i]);
            printf("\n");

    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值