题目描述
给出一棵二叉树的中序与后序排列。求出它的先序排列。(约定树结点用不同的大写字母表示,长度< =8)。
输入
两行,每行一个字符串,分别表示中序和后序排列
输出
一个字符串,表示所求先序排列
样例输入
BADC BDCA样例输出
ABCD
#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <vector>
#include <map>
#include <queue>
#include <cstdio>
#include <string>
#include <stack>
#include <set>
#define IOS ios::sync_with_stdio(false), cin.tie(0)
using namespace std;
typedef long long ll;
string ans;
//dfs求中序遍历序列为a,后序遍历为b的先序序列
void dfs(string a,string b){
if(a.length()==0)return ;
ans.push_back(b[b.length()-1]);
char c=b[b.length()-1];
int mid=0;
while(a[mid]!=c){
mid++;
}
dfs(a.substr(0,mid),b.substr(0,mid));//左子树
dfs(a.substr(mid+1,a.length()-mid-1),b.substr(mid,b.length()-mid-1));//右子树
return ;
}
int main()
{
IOS;
string a,b;
cin>>a>>b;
dfs(a,b);
cout<<ans<<endl;
getchar();
getchar();
return 0;
}