题目描述
给出一棵二叉树的中序与后序排列。求出它的先序排列。(约定树结点用不同的大写字母表示,长度\le 8≤8)。
输入格式
22行,均为大写字母组成的字符串,表示一棵二叉树的中序与后序排列。
输出格式
11行,表示一棵二叉树的先序。
输入输出样例
输入 #1复制
BADC BDCA
输出 #1复制
ABCD
#include <bits/stdc++.h>
using namespace std;
char tree[100000],t=0;
double n;
string inor, post;
void build(int inl,int inr,int pol,int por) {
int t = inl;
if (inl == inr) {
printf("%c",inor[inl]);
return;
}
for (; t <= inr; t++) {
if (inor[t] == post[por])break;
}
int llen = t - inl;
int rlen = inr - t;
printf("%c", post[por]);
if(llen>0)build(inl,inl+llen-1, pol, pol+llen-1);
if(rlen>0)build(t + 1, inr, por - rlen, por - 1);
}
int main() {
ios::sync_with_stdio(0);
cin >> inor >> post;
build(0,inor.size()-1,0,post.size()-1);
return 0;
}