题目描述
二叉树的前序、中序、后序遍历的定义: 前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树; 中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树; 后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。 给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。
输入描述:
两个字符串,其长度n均小于等于26。
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C…最多26个结点。
输出描述:
输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。
示例1
输入
复制
ABC
BAC
FDXEAG
XDEFAG
输出
复制
BCA
XEDGAF
#include<iostream>
#include<string>
using namespace std;
void pre_in_to_PostOrder(string pre,string in,string &post,
int post_left,int post_right,
int pre_left,int pre_right,
int in_left,int in_right);
string pre,in,res;
int main(){
while(getline(cin,pre)&&getline(cin,in)){
res="";
int len=pre.size();
for(int i=0;i<len;i++)res+=" ";
pre_in_to_PostOrder(pre,in,res,0,len-1,0,len-1,0,len-1);
cout<<res<<endl;
}
return 0;
}
void pre_in_to_PostOrder(string pre,string in,string &post,
int post_left,int post_right,
int pre_left,int pre_right,
int in_left,int in_right){
if(post_left<=post_right&&pre_left<=pre_right&&in_left<=in_right){
int pos,left_child_len,right_child_len;
post[post_right]=pre[pre_left];
for(pos=0;in[pos]!=pre[pre_left];pos++);
left_child_len=pos-in_left;
right_child_len=in_right-pos;
pre_in_to_PostOrder(pre,in,post,
post_left,post_left+left_child_len-1,
pre_left+1,pre_left+left_child_len,
in_left,in_left+left_child_len-1);
pre_in_to_PostOrder(pre,in,post,
post_left+left_child_len,post_right-1,
pre_left+left_child_len+1,pre_right,
pos+1,in_right);
}
}