题目描述
给出一棵二叉树的中序与后序排列。求出它的先序排列。(约定树结点用不同的大写字母表示,长度<=8)。
输入
每个测试文件只包含一组测试数据,每组输入包含两行,第一行输入一个字符串表示二叉树的中序排列,第二行输入一个字符串表示二叉树的后序排列。
输出
对于每组输入数据,输出二叉树的先序排列。
样例输入
BADC BDCA
样例输出
ABCD
参考代码:
#include<bits/stdc++.h>
using namespace std;
string s1,s2;
int len;
int find(char x){
for(int i=0;i<=len;i++)
if(s1[i]==x)
return i;
}
void pre(int l1,int r1,int l2,int r2){
int ip=find(s2[r2]);
cout<<s1[ip];
if(ip>l1)pre(l1,ip-1,l2,ip-l1+l2-1);
if(ip<r1)pre(ip+1,r1,ip+l2-l1,r2-1);
}
int main(){
cin>>s1>>s2;
len=s1.size()-1;
pre(0,len,0,len);
return 0;
}