1127 ZigZagging on a Tree

给定二叉树的中序和后序遍历,实现层次遍历,按ZigZag顺序输出。解题方法涉及双端队列模拟左右方向变化,代码相对复杂。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述在这里插入图片描述

题目大意:

给定二叉树的中序和后序遍历,输出“层次”遍历,这个层次遍历从根节点的子节点开始,先从左到右输出,然后从右到左输出。。。循环往复。

解题思路:

这个题我写的复杂了一点,关于输出哪里我用了两个双端队列模拟了输出的扩展情况,即从左到右和从右到左,所以代码较难理解。维护一个度参数根据奇偶度判断是从右到左还是从左到右输出会方便很多。
代码如下:

#include<iostream>
#include<vector>
#include<queue>
#include<deque>
#include<cstdio>
using namespace std;
int n,post[40],in[40];
struct node
{
	int data;
	node* lchild;
	node* rchild;
};
node* create(int postl,int postr,int inl,int inr)//建树 
{
	if(postr<postl)return NULL;
	node* root=new node;
	root->data=post[postr];
	int k;
	for(int i=inl;i<=inr;i++)
	{
		if(in[i]==post[postr])
		{
			k=i;
			break;
		}
	}
	int numleft=k-inl-1;
	root->lchild=create(postl,postl+numleft,inl,k-1);
	root->rchild=create(postl+numleft+1,postr-1,k+1,inr);
	return root;
}
void bfs(node* root)//层次遍历 
{
	deque<node*>q1,q2;//互换扩展节点 
	queue<int>q3;//保存输出序列 
	q1.push_back(root);
	q3.push(root->data);
	int flag=1,num=0;
	while(!q1.empty()||!q2.empty())//所有节点都扩展完成 
	{
		while(!q1.empty())//q1是从左到右扩展 
		{
			node* tmp=q1.front();
			q1.pop_front();
			if(tmp->lchild!=NULL)
			{
				q2.push_back(tmp->lchild);
				node* kk=tmp->lchild;
				q3.push(kk->data);
			} 
			if(tmp->rchild!=NULL)
			{
				q2.push_back(tmp->rchild);
				node* kk=tmp->rchild;
				q3.push(kk->data);
			}
		}
		while(!q2.empty())//q2是从右到左扩展 
		{
			node* tmp=q2.back();
			q2.pop_back();
			if(tmp->rchild!=NULL)
			{
				q1.push_front(tmp->rchild);
				node* kk=tmp->rchild;
				q3.push(kk->data);
			}
			if(tmp->lchild!=NULL)
			{
				q1.push_front(tmp->lchild);
				node* kk=tmp->lchild;
				q3.push(kk->data);
			}
		}
	}
	cout<<q3.front();
	q3.pop();
	while(!q3.empty())
	{
		cout<<' '<<q3.front();
		q3.pop();
	}
	cout<<endl;
}
int main()
{
	cin>>n;
	for(int i=0;i<n;i++)cin>>in[i];
	for(int i=0;i<n;i++)cin>>post[i];
	node* root=create(0,n-1,0,n-1);
	bfs(root);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值