題意: 給出一個樹的中序和後序遍歷結果,求它的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;
}