CD 168 二叉树的按层打印与ZIgZag打印

题目描述
给定一颗二叉树,分别实现按层和 ZigZag 打印二叉树。
ZigZag遍历: 意思是第一层从左到右遍历,第二层从右到左遍历,依次类推。
输入描述:
第一行输入两个整数 n 和 root,n 表示二叉树的总节点个数,root 表示二叉树的根节点。
以下 n 行每行三个整数 fa,lch,rch,表示 fa 的左儿子为 lch,右儿子为 rch。(如果 lch 为 0 则表示 fa 没有左儿子,rch同理)
输出描述:
先输出按层打印,再输出按ZigZag打印。
示例1
输入
复制
8 1
1 2 3
2 4 0
4 0 0
3 5 6
5 7 8
6 0 0
7 0 0
8 0 0
输出
复制
Level 1 : 1
Level 2 : 2 3
Level 3 : 4 5 6
Level 4 : 7 8
Level 1 from left to right: 1
Level 2 from right to left: 3 2
Level 3 from left to right: 4 5 6
Level 4 from right to left: 8 7

zlgzag打印时一样按照层序打印的顺序一样,在输出时输入到一个栈中,然后在从栈中输出。

#include<iostream>
#include<queue>
#include<stack>
#include<deque>
using namespace std;

struct node
{
	int lch,rch;
	node(int x=0,int y=0):lch(x),rch(y){};
};
node a[500000];

void printLevel(int root)
{
	queue<int> q;
	q.push(root);
	int level=1;
	while(!q.empty())
	{
		int len=q.size();
		cout<<"Level "<<level++<<" :";
		for(int i=0;i<len;i++)
		{
			int k=q.front();
			q.pop();
			cout<<" "<<k;
			
			if(a[k].lch)
			   q.push(a[k].lch);
			if(a[k].rch)
			   q.push(a[k].rch);
		}
		cout<<endl;
	}
}

void ZigZag(int root)
{
	queue<int> q;
	stack<int> st;
	q.push(root);
	int level=1;
	while(!q.empty())
	{
		
		
		if(level%2==0)//逆序输入到队列中 
		{
			cout<<"Level "<<level<<" from right to left:";
			int len=q.size();
			for(int i=0;i<len;i++)
			{
				int k=q.front();
				q.pop();
				st.push(k);
				if(a[k].lch)
				    q.push(a[k].lch);
				if(a[k].rch )
				    q.push(a[k].rch);
			}
			while(!st.empty())
			{
				cout<<" "<<st.top();
				st.pop();
			}
		}
		else
		{
			cout<<"Level "<<level<<" from left to right:";
			int len=q.size();
			for(int i=0;i<len;i++)
			{
				int k=q.front();
				q.pop();
				cout<<" "<<k;
				if(a[k].lch)
				    q.push(a[k].lch);
				if(a[k].rch )
				    q.push(a[k].rch);
			}
		}
		cout<<endl;	
		level++; 
	}
}


int main()
{
	int n,root;
	scanf("%d%d",&n,&root);
	for(int i=1;i<=n;i++)
	{
		int fa,lch,rch;
		scanf("%d%d%d",&fa,&lch,&rch);
		a[fa].lch=lch;
		a[fa].rch=rch;
	}
 
	printLevel( root);
	ZigZag(root);
	
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值