AcWing 1620. Z 字形遍历二叉树
原题链接
简单
作者:
RainSure
,
2022-02-26 09:20:50
,
所有人可见
,
阅读 235
层序遍历的过程中 奇数层翻转就可以了
#include<iostream>
#include<cstring>
#include<unordered_map>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 40;
unordered_map<int,int> l, r, pos;
int in[maxn], post[maxn];
int n;
int build(int il, int ir, int pl, int pr)
{
int root = post[pr];
int k = pos[root];
if(il < k) l[root] = build(il, k - 1, pl, pl + (k - 1 - il));
if(k < ir) r[root] = build(k + 1, ir, pl + k - 1 - il + 1, pr - 1);
return root;
}
void bfs(int root)
{
queue<int> q;
vector<int> res;
q.push(root);
int step = 0;
while(q.size())
{
vector<int> temp;
while(q.size())
{
auto t = q.front();
temp.push_back(t);
q.pop();
}
for(auto t : temp){
if(l.count(t)) q.push(l[t]);
if(r.count(t)) q.push(r[t]);
}
if(++ step % 2) reverse(temp.begin(), temp.end());
for(auto t : temp) res.push_back(t);
}
for(int i = 0; i < res.size(); i ++){
if(i != 0) cout << " ";
cout << res[i];
}
}
int main()
{
cin >> n;
for(int i = 0; i < n; i ++){
cin >> in[i];
pos[in[i]] = i;
}
for(int i = 0; i < n; i ++) cin >> post[i];
int root = build(0, n - 1, 0, n - 1);
bfs(root);
return 0;
}