问题:给一颗二叉树的前序遍历和中序遍历 ,给出后序遍历。
- 前序遍历 根 左 右
- 中序遍历 左 根 右
- 后序遍历 左 右 根
给一个例子:
A B D E C
B D E A C
例子中A为根节点 A的左子树是 BDE 右子树。考虑递归。
#include<bits/stdc++.h>
using namespace std;
string str1,str2,ans;
int cnt;
void solve(string a,string b){
if(a.size()==0) return ;
if(a.size()==1){
ans+=a[0];//序列只有一个节点
return ;
}
int tt=b.find(a[0]);
solve(a.substr(1,tt),b.substr(0,tt));//先左子树
solve(a.substr(tt+1,a.size()-tt-1),b.substr(tt+1,b.size()-tt-1));//右子树
ans+=a[0];//根节点
}
int main(){
while(cin>>str1>>str2){
ans="";
solve(str1,str2);
cout<<ans<<endl;
}
return 0;
}