链接:https://www.nowcoder.com/questionTerminal/6e732a9632bc4d12b442469aed7fe9ce
来源:牛客网
二叉树的前序、中序、后序遍历的定义: 前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树; 中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树; 后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。 给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。
输入描述:
两个字符串,其长度n均小于等于26。 第一行为前序遍历,第二行为中序遍历。 二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。
输出描述:
输入样例可能有多组,对于每组测试样例, 输出一行,为后序遍历的字符串。
示例1
输入
ABC BAC FDXEAG XDEFAG
输出
BCA XEDGAF
分析:
根 左 右
前序 F | D X E | A G
左 根 右
中序 X D E | F | A G
左 右 根
后序 | | F
递归 递归
详见代码:
#include<bits/stdc++.h>
using namespace std;
struct node{
char val;
node *left;
node *right;
node(){
val = 0;left = NULL;right = NULL;
}
};
node* build(string a,string b){//重建二叉树
node *t = NULL;
if(a.length()>0){
t = new node();
t->val = a[0];
int index = 0;
for(int i=0;i<b.length();i++){
if(b[i]==a[0]){
index = i;break;
}
}
t->left = build(a.substr(1,index),b.substr(0,index));//左子树
t->right = build(a.substr(index+1),b.substr(index+1)); //右子树
}
return t;
}
void fun(node* t){//后序遍历
if(t->left!=NULL) fun(t->left);
if(t->right!=NULL) fun(t->right);
cout << t->val;
}
int main(){
string a,b;
while(cin>>a>>b){
node *t = build(a,b);
fun(t);
cout << endl;
}
return 0;
}