给出一棵二叉树的中序和后序遍历,求它的前序遍历。(树结点用不同的大写字母表示,长度小于等于26。)
Input
本问题有多组测试数据,每组测试数据有两行,每行都是由大写字母组成,分别表示一颗二叉树的中序和后序遍历。
Output
根据给定的中序和后序遍历,输出相应的前序遍历。
Sample Input
BADC
BDCA
Sample Output
ABCD
#include<bits/stdc++.h>
using namespace std;
const int MAXN=100005;
int tot,root,n,l;
char a[MAXN],b[MAXN];
struct tree_node
{
int ch[2];
char num;
}t[MAXN];
int dfs(int l,int r,int beg)
{
if(l>r)return 0;
for(int i=beg;i<=n;++i)
{
for(int j=l;j<=r;++j)
{
if(a[i]==b[j])
{
int new_node=++tot;
t[new_node].num=a[i];
t[new_node].ch[0]=dfs(l,j-1,i+1);
t[new_node].ch[1]=dfs(j+1,r,i+1);
return new_node;
}
}
}
}
string ans;
void go(int x)
{
ans+=t[x].num;
if(t[x].ch[0])go(t[x].ch[0]);
if(t[x].ch[1])go(t[x].ch[1]);
}
int main()
{
while(scanf("%s%s",b+1,a+1)!=EOF)
{
n=strlen(a+1);
reverse(a+1,a+1+n);
tot=0;
root=dfs(1,n,1);
ans.clear();
go(1);
printf("%s\n",ans.c_str());
}
}