总时间限制:
1000ms
内存限制:
65536kB
描述
给定一棵二叉树的前序遍历和中序遍历的结果,求其后序遍历。
输入
输入可能有多组,以EOF结束。
每组输入包含两个字符串,分别为树的前序遍历和中序遍历。每个字符串中只包含大写字母且互不重复。
输出
对于每组输入,用一行来输出它后序遍历结果。
样例输入
DBACEGF ABCDEFG
BCAD CBAD
样例输出
ACBFGED
CDAB
#include <iostream>
#include <queue>
#include <string>
#include <string.h>
using namespace std;
struct node{
char name;
node* lchild;
node* rchild;
node(char n){
name=n;lchild=NULL;rchild=NULL;
}
};
node* maketree(string pre,string mid){
node* root = new node(pre[0]);
int lsubsize = mid.find(pre[0]);
int rsubsize = pre.size()-1-lsubsize;
if(lsubsize){
root->lchild= maketree(pre.substr(1,lsubsize),mid.substr(0,lsubsize));
}
if(rsubsize){
root->rchild= maketree(pre.substr(lsubsize+1,rsubsize),mid.substr(lsubsize+1,rsubsize));
}
return root;
}
void backfind(node* root){
if(root->lchild) backfind(root->lchild);
if(root->rchild) backfind(root->rchild);
cout<<root->name;
}
int main(){
string pre,mid;
while(cin>>pre>>mid){
node* root = maketree(pre,mid);
backfind(root);
cout<<endl;
}
return 0;
}