pta甲級 1127 ZigZagging on a Tree (30分)

鏈接: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;
}

 

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