UVA 548 —— 二叉树的递归遍历

已知二叉树的中序遍历和后序遍历,构建二叉树,求叶子到根的最小路径权值和;

后序遍历的最后一个字符即为二叉树的根结点,然后在中序遍历中找到这个根结点的位置,根结点的左边序列即为该根的左子树,右边序列即为右子树,然后再在后序遍历中找左右子树的根结点,以此类推,用递归遍历。


#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
using namespace std;
const int maxn = 1e4+5;
int in_order[maxn], post_order[maxn];
int lch[maxn], rch[maxn];
int cnt;

bool read_input(int* a){
    cnt = 0;
    string s;
    if(!getline(cin, s))    return false;
    int len = (int)s.size();
    int tmp = 0;
    for(int i = 0;i<len;i++){
        if(s[i] == ' '){
            a[cnt++] = tmp;
            tmp = 0;
            continue;
        }
        tmp = tmp*10+(s[i]-'0');
    }
    a[cnt++] = tmp;
    if(cnt > 0) return true;
    else    return false;
}

int build(int L1, int R1, int L2, int R2){
    if(L1 > R1) return 0;       //空树
    int root = post_order[R2];
    int i;
    for(i = L1;i<=R1;i++){
        if(in_order[i] == root)
            break;
    }
    int k = i-L1;
    lch[root] = build(L1, i-1, L2, L2+k-1);
    rch[root] = build(i+1, R1, L2+k, R2-1);
    return root;
}

int ans, tmp;
void dfs(int u, int sum){
    if(u == 0)  return;
    sum += u;
    if(!lch[u] && !rch[u]){     //叶子
        if(ans > sum || (ans == sum && tmp > u)){
            ans = sum;
            tmp = u;
        }
        return;
    }
    dfs(lch[u], sum);
    dfs(rch[u], sum);
}

int main(){
    while(read_input(in_order)){
        read_input(post_order);
        build(0, cnt-1, 0, cnt-1);
        ans = INF;
        dfs(post_order[cnt-1], 0);
        cout<<tmp<<endl;
    }
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值