Uva-536 Tree Recovery

题目链接:Tree Recovery

题目大意:已知一棵树的先序遍历和中序遍历顺序,求它的后序遍历顺序。

解题思路:关键在于找到父结点的位置,然后递归建树即可。

代码如下:

#include <map>
#include <stack>
#include <queue>
#include <cstdio>
#include <vector>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int inf = 0x3f3f3f3f;
const int maxn = 1e4 + 15;

int rch[maxn], lch[maxn], root;
string Prt, In, s;

void Init(){
    memset(lch, 0, sizeof lch);
    memset(rch, 0, sizeof rch);
}

void Build(const string& a, const string& b){
    if(a.size() <= 1 || b.size() <= 1)
        return;
    int rt = b[0];
    auto it = find(a.begin(), a.end(), rt);
    string la(a.begin(), it); ++it;
    string ra(it, a.end());
    int l = la.size(), r = ra.size();
    string lb(b.begin() + 1, b.begin() + l + 1);
    string rb(b.begin() + l + 1, b.begin() + l + r + 1);
    if(!lb.empty()) lch[rt] = lb[0]; 
    if(!rb.empty()) rch[rt] = rb[0];
    Build(la, lb);
    Build(ra, rb);
}

void Print(int u){
    if(lch[u] > 0) 
        Print(lch[u]);
    if(rch[u] > 0) 
        Print(rch[u]);
    cout << (char)u;
    return;
}

int main(){
    ios::sync_with_stdio(false);
    #ifdef LOCAL
    freopen("in.txt", "r", stdin);
    #endif
    while(getline(cin, s)){
        Init();
        stringstream ss(s);
        ss >> Prt; ss >> In;
        root = Prt[0];
        Build(In, Prt);
        Print(root);
        cout << endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值