链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805349394006016
题意:给出n个点的二叉树的中序遍历序列和后序遍历序列。按“Z”型输出层序遍历序列。
思路:直接大模拟,建树硬怼。详情看注释。
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 100;
/*
这个题中我存的值都是中序遍历的下标
*/
int po[N],in[N],n;
//po,in分别对应中序和后序
map<int,int> mp,pos;
//mp[x]=y:表示值x在中序遍历的下标
//pos[x]=y:表示值x在后序遍历的下标
int dep[N],lay[N],cnt=0;
//dep[i]:中序遍历中下标为i的值的深度
//lay:储存每一层在中序遍历的下标
vector<int> ans;
//储存答案
struct node{
//初值为0
int lson,rson;
//tree[i].lson:中序下标为i的左孩子的中序下标
//tree[i].rson:中序下标为i的右孩子的中序下标
}tree[N];
//建树函数
//u:当前节点的中序下标
//l:当前节点所划分区间左端点的中序下标
//r:当前节点所划分区间右端点的中序下标
void build(int u,int l,int r){
if(l>=r) return ;
//如果l<u则代表u有左孩子
if(l<u){
//u的左孩子就是[l,u-1]这个区间内后序下标最大的节点
int ls=l;
for(int i=l;i<u;i++){
if(pos[in[i]]>pos[in[ls]]){
ls=i;
}
}
tree[u].lson=ls;
dep[ls]=dep[u]+1;
//ls划分的区间为[l,u-1]
build(ls,l,u-1);
}
//如果u<r则代表u有右孩子
if(u<r){
//u的右孩子就是[u+1,r]这个区间内后序下标最大的节点
int rs=r;
for(int i=u+1;i<=r;i++){
if(pos[in[i]]>pos[in[rs]]){
rs=i;
}
}
tree[u].rson=rs;
dep[rs]=dep[u]+1;
//rs划分的区间为[u+1,r]
build(rs,u+1,r);
}
}
void bfs(int root){
queue<int> q;
//now:当前节点下标
//nowdep:上一节点深度,注意这个初值0
int now,nowdep=0;
q.push(root);
while(!q.empty()){
now=q.front();
q.pop();
//因为是广搜,如果当前节点深度与上一节点深度不同
//说明上一层的所有节点都在lay数组中
if(dep[now]!=nowdep){
//如果上一节点深度为奇数那么要倒着放入ans
if(nowdep&1){
for(int i=cnt;i>=1;i--)
ans.push_back(lay[i]);
}
else{
for(int i=1;i<=cnt;i++)
ans.push_back(lay[i]);
}
//cnt归为0,更新nowdep
cnt=0;
nowdep=dep[now];
}
lay[++cnt]=now;
if(tree[now].lson)
q.push(tree[now].lson);
if(tree[now].rson)
q.push(tree[now].rson);
}
//最后一层的节点没有放入ans
if(nowdep&1){
for(int i=cnt;i>=1;i--)
ans.push_back(lay[i]);
}
else{
for(int i=1;i<=cnt;i++)
ans.push_back(lay[i]);
}
int siz=ans.size();
for(int i=0;i<siz;i++){
cout<<in[ans[i]];
if(i!=siz-1)
cout<<" ";
}
}
int main(void){
cin>>n;
for(int i=1;i<=n;i++){
cin>>in[i];
mp[in[i]]=i;
}
for(int i=1;i<=n;i++){
cin>>po[i];
pos[po[i]]=i;
}
int root=mp[po[n]];
dep[root]=1;
build(root,1,n);
bfs(root);
return 0;
}