PAT——1127 ZigZagging on a Tree 甲级

1127 ZigZagging on a Tree

题目

https://pintia.cn/problem-sets/994805342720868352/problems/994805349394006016

题意

给出一棵树的中序和后序序列,要求按Z字型输出该数的层序序列

代码解析

详见参考文章,里面博主说的很详细了,在此解释一下df函数中的第一个参数index:

因为是地址传递,所以这个参数相当于先把postr赋值给root,然后在下一层递归时把root的左孩子和右孩子赋值给tree[index][0]和tree[index][1],以此类推。所以即使没有赋值语句,但执行完dfs后就完成了对tree数组的赋值

AC代码

#include<bits/stdc++.h>
using namespace std;
int post[35],in[35];
vector<int> res[35];
int n,root,tree[35][2];
struct node{
	int index,depth;
};
void dfs(int &index,int inl,int inr,int postl,int postr)
{
	if(inl>inr) return;
	index=postr;// 为上一层index对应的地址赋值 
	int i=0;
	while(in[i]!=post[postr]) i++;//找到根的位置
	dfs(tree[index][0],inl,i-1,postl,postl+(i-inl)-1);
	dfs(tree[index][1],i+1,inr,postl+(i-inl),postr-1); 
}
void bfs()
{
	queue<node> q;
	q.push({root,0});
	while(!q.empty())
	{
		node tmp=q.front();
		q.pop();
		res[tmp.depth].push_back(post[tmp.index]);
		if(tree[tmp.index][0]) 
			q.push({tree[tmp.index][0],tmp.depth+1});
		if(tree[tmp.index][1]) 
			q.push({tree[tmp.index][1],tmp.depth+1});
	}
}
int main()
{
	cin>>n;
	for(int i=1;i<=n;i++) cin>>in[i];
	for(int i=1;i<=n;i++) cin>>post[i];
	dfs(root,1,n,1,n);
	bfs();
	cout<<res[0][0];
	for(int i=1;i<35;i++)
	{
		if(i%2)
			for(int j=0;j<res[i].size();j++)
				cout<<" "<<res[i][j];
		else
			for(int j=res[i].size()-1;j>=0;j--)
				cout<<" "<<res[i][j];
	}
}

参考

PAT 1127. ZigZagging on a Tree (30)-甲级

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值