题目描述
给出一棵二叉树的中序与后序排列。求出它的先序排列。(约定树结点用不同的大写字母表示,长度<=8)。
输入输出格式
输入格式:2行,均为大写字母组成的字符串,表示一棵二叉树的中序与后序排列。
输出格式:1行,表示一棵二叉树的先序。
输入输出样例
输入样例#1: 复制
BADC BDCA
思路:后序遍历的最后一个元素必定是根结点,这样就可以找出中序遍历的根结点,输出该结点,将中序遍历的字符串分为两部分,重复递归即可
附上AC代码:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <list>
#include <map>
#include <stack>
#include <queue>
using namespace std;
#define ll long long
char z[100],h[100];
void solve(int z1,int z2,int h1,int h2)
{
if(z1 > z2)
return;
cout << h[h2];
int i = z1;
while(z[i] != h[h2])
i++;
i-=z1;
solve(z1,z1+i-1,h1,h1+i-1);//这部分得自己画画,比较下,直接看代码比较难懂
solve(z1+i+1,z2,h1+i,h2-1);//这部分得自己画画,比较下,直接看代码比较难懂
}
int main()
{
while(cin >> z >> h)
{
int z2,h2;
z2 = strlen(z)-1;
h2 = strlen(h)-1;
solve(0,z2,0,h2);
cout << endl;
}
//cout << "AC" <<endl;
return 0;
}