题目链接: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;
}