1127 ZigZagging on a Tree(無需建樹)

題目

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章