题意: 给出一个树的中序和后序遍历结果,求它的Z字型层序遍历,也就是偶数层从右往左,奇数层从左往右遍历
tip:无需建树,递归即可
#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
int inorder[33],post[33];
map<int,vector<int>>ans;
map<int ,int>index;
int height=0;
void getlevel(int s,int e,int root,int h) {
if(s>e)
return ;
height=max(height,h);//更新最大层数
ans[h].push_back(post[root]);
int t=index[post[root]];
getlevel(s,t-1,root-(e-t)-1,h+1);//左子树
getlevel(t+1,e,root-1,h+1);//右子树
}
int main() {
int n;
cin>>n;
for(int i=0; i<n; ++i) {
cin>>inorder[i];
index[inorder[i]]=i;
}
for(int i=0; i<n; ++i)
cin>>post[i];
getlevel(0,n-1,n-1,1);
cout<<ans[1][0];
for(int i=2; i<=height; ++i) {
if(i%2)
reverse(ans[i].begin(),ans[i].end());//奇数层逆序即可
for(int j=0; j<ans[i].size(); ++j)
cout<<" "<<ans[i][j];
}
return 0;
}