问题描述
给出一棵二叉树的中序与后序排列。求出它的先序排列。(约定树结点用不同的大写字母表示,长度<=8)。
给出一棵二叉树的中序与后序排列。求出它的先序排列。(约定树结点用不同的大写字母表示,长度<=8)。
输入格式
两行,每行一个字符串,分别表示中序和后序排列
输出格式
一个字符串,表示所求先序排列
样例输入
BADC
BDCA
样例输入
BADC
BDCA
样例输出
ABCD
算法思想:我们先去寻找这棵树的根,即后序排列的最后一个元素,然后在中序排列中找到它,此时在中序排列中,其左边就是左子树,右边就是右子树,分别记录下左子树和右子树的元素个数,就能同时在后序排列中找到左右子树的分布区间,对子树继续递归重复以上过程即可,代码如下。
#include<cstdio>
#include<algorithm>
#include<queue>
#include<iostream>
#include<cstring>
using namespace std;
char mid[10];
char hou[10];
int len;
void Seek(int first,int last,int mfir,int mlast)
{
if(first>last||mfir>mlast)
return ;
char ch=hou[last];
cout<<ch;
for(int i=mfir;i<=mlast;i++)
{
if(mid[i]==ch)
{
Seek(first,first+i-1-mfir,mfir,i-1);
Seek(last-mlast+i,last-1,i+1,mlast);
break;
}
}
}
int main()
{
scanf("%s",mid);
scanf("%s",hou);
len=strlen(hou);
Seek(0,len-1,0,len-1);
return 0;
}