题目大意:给定一个中序和后序序列,求层次遍历,注意不是普通的层次,这个题目的输出要求是每隔一层要逆序输出。
正常中后序建树,数据范围小就可以不用哈希表优化建树,然后宽搜一遍把层次遍历存一下,然后将需要逆序的层翻转一下就行了。
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
const int N = 1000;
int post[N],iner[N],f,c;
vector<int>ans[100];
struct node
{
int v;
node *left,*right;
node(int x) : v(x),left(NULL),right(NULL){}
}*tr;
node *build(int postL,int postR,int inL,int inR)
{
if(postL > postR) return NULL;
node * t = new node(post[postR]);
int k = inL;
while(post[postR] != iner[k]) k ++;
t->left = build(postL,postL + k - inL - 1,inL,k - 1);
t->right = build(postL + k - inL,postR - 1,k + 1,inR);
return t;
}
void bfs(node *tr)
{
queue<pair<node*,int>>que;
que.push({tr,0});
while(que.size())
{
auto x = que.front();que.pop();auto t = x.first;
f = x.second;
ans[x.second].push_back(t->v);
if(t->left != NULL) que.push({t->left,x.second + 1});
if(t->right != NULL ) que.push({t->right,x.second + 1});
}
}
int main()
{
int n;
cin >> n;
for(int i = 0; i < n; i ++) cin >> iner[i];
for(int i = 0; i < n; i ++) cin >> post[i];
tr = build(0,n - 1,0,n - 1);
bfs(tr);
for(int i = 0; i <= f; i ++)
if(i % 2 == 0) reverse(ans[i].begin(),ans[i].end());
for(int i = 0; i <= f; i ++)
for(auto t : ans[i])
{
if(c != 0) cout << ' ';
cout << t;c = 1;
}
return 0;
}