uva 536 - Tree Recovery 入门经典II 第六章 数据结构基础 习题6-3

题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=477


题意:给出一颗树的前序、中序, 求后序。


思路:同例题6-8。


说明:虽然比较简单,但是自己能做出来还是挺有收获的。

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;

const int maxn = 100 + 10;
char pre_order[maxn],in_order[maxn];
int  lch[maxn],rch[maxn];

int built(int L1,int R1,int L2,int R2){
    if(L2>R2) return 0;

    //根为前序中第一个元素
    int root = pre_order[L1];

    //在中序里面找根
    int p = L2;
    while(in_order[p]!=root) p++;

    //cnt用于计算左子树有多少元素,剩下的就是右子树的。
    int cnt=p-L2;

    //分别求左子树的根、右子树的根。
    lch[root]=built(L1+1, L1+cnt, L2,  p-1);
    rch[root]=built(L1+cnt+1, R1, p+1, R2);

    return root;
}

//后序遍历,先输出左子树,再输出右子树,再输出根。
void print(int root){
    if(lch[root]!=0) print(lch[root]);
    if(rch[root]!=0) print(rch[root]);
    printf("%c",root);
}

int main(){
    while(cin >> pre_order){
        cin >> in_order;
        int len=strlen(pre_order);
        built(0,len-1,0,len-1);

        print(pre_order[0]);
        printf("\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值