题目
这个题和树的遍历那题一个思路,唯一改变的地方就是这里要求要先镜像二叉树,所以这里在递归时,先从右子树开始进入递归函数(将build函数上下调换位置)即可。
代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 35;
int pre[N], in[N], p[N];
vector<int> level[N];
/*
void build (int prel, int prer, int inl, int inr, int d)
{
if (prel > prer) return;
int val = pre[prel];
level[d].push_back(val);
int k = p[val];
build(prel + 1, prel + k - 1 - inl, inl, k - 1, d + 1);
build(prel + k - inl, prer, k + 1, inr, d + 1);
}
*/
void build (int prel, int prer, int inl, int inr, int d)
{
if (prel > prer) return;
int val = pre[prel];
level[d].push_back(val);
int k = p[val];
build(prel + k - inl + 1, prer, k + 1, inr, d + 1);
build(prel + 1, prel + k - inl, inl, k - 1, d + 1);
}
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i ++ ) cin >> in[i];
for (int i = 0; i < n; i ++ ) cin >> pre[i];
for (int i = 0; i < n; i ++ ) p[in[i]] = i;
build(0, n - 1, 0, n - 1, 0);
bool flag = false;
for (int i = 0; i < n; i ++ )
{
if (!flag)
{
for (int x : level[i])
cout << x;
flag = true;
}
else
{
for (int x : level[i])
cout << ' ' << x;
}
}
return 0;
}