uva 536

给出二叉树先序和中序遍历打印出后序遍历结果。
这一题跟之前的 uva 548有一些类似,可以对照着学习
代码如下,特备注意dfs的时候递归条件心里要清楚,否则出错很麻烦:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <set>
using namespace std;

const int maxn = 1000 + 10;

string pre_order,in_order;
int lch[maxn],rch[maxn];

int build(int l1,int r1,int l2,int r2){
    if(l1>r1) return 0;
    int root = pre_order[l1]-'A'+1;
    int p = l2;
    while(in_order[p]-'A'+1 != 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 solve(int root){
    if(lch[root]) solve(lch[root]);
    if(rch[root]) solve(rch[root]);
    char ch = 'A'+root-1;
    cout<<ch;
}

int  main(){
    while(cin >> pre_order ){
        memset(lch,0,sizeof(lch));
        memset(rch,0,sizeof(rch));
        cin >> in_order;
        int len = pre_order.length();
        build(0,len-1,0,len-1);
        solve(pre_order[0]-'A'+1);
        cout<<endl;
        /*for(int i = 0;i<10;i++){
            cout<<i<<":"<<lch[i]<<","<<rch[i]<<endl;
        }*/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值