求前序遍历

给出一棵二叉树的中序和后序遍历,求它的前序遍历。(树结点用不同的大写字母表示,长度小于等于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());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值