给出二叉树先序和中序遍历打印出后序遍历结果。
这一题跟之前的 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;
}
时间: 2024-10-09 11:32:12