-
题目描述:
-
二叉树的前序、中序、后序遍历的定义:
前序遍历:对任一子树,先访问跟,然后遍历其左子树,最后遍历其右子树;
中序遍历:对任一子树,先遍历其左子树,然后访问根,最后遍历其右子树;
后序遍历:对任一子树,先遍历其左子树,然后遍历其右子树,最后访问根。
给定一棵二叉树的前序遍历和中序遍历,求其后序遍历(提示:给定前序遍历与中序遍历能够唯一确定后序遍历)。
-
输入:
-
两个字符串,其长度n均小于等于26。
第一行为前序遍历,第二行为中序遍历。
二叉树中的结点名称以大写字母表示:A,B,C....最多26个结点。
-
输出:
-
输入样例可能有多组,对于每组测试样例,
输出一行,为后序遍历的字符串。
-
样例输入:
-
ABC BAC FDXEAG XDEFAG
-
样例输出:
-
BCA XEDGAF
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<stack>
#include<algorithm>
#include<cmath>
using namespace std;
typedef struct tree{
char num;
struct tree *left;
struct tree *right;
}tree,*linktree;
linktree creat(char *qian,char *zhong,int num){
if(num<=0 ) return NULL;
linktree t=new tree;
t->num=qian[0];
int index=0;
for(int i=0;i<=num;i++){
if(zhong[i]==qian[0]){
index=i;
break;
}
}
t->left=creat(qian+1,zhong,index);
t->right=creat(qian+index+1,zhong+index+1,num-index-1);
return t;
}
void hou(linktree head){
if(head){
hou(head->left);
hou(head->right);
cout<<head->num;
}
}
int main(){
char qian[1000],zhong[1000];
while(cin>>qian){
cin>>zhong;
int len=strlen(qian);
linktree head=creat(qian,zhong,len);
hou(head);
cout<<endl;
}
return 0;
}