按层遍历二叉树(队列实现)

按层遍历二叉树的思路:

1)创建一个队列用于保存指向Node节点的指针

2) 每遇到一个节点就遍历该节点,然后将该节点不为空的孩子压入栈中

3) 从栈中取出一个节点,回到第二步

#include <iostream>
#include <queue>
using namespace std;
struct Node 
{
	int num;
	Node* pLeft;
	Node* pRight;
};
void insert(Node* &p,int num)
{
	Node* pTmp=new Node();
	pTmp->num=num;
	pTmp->pLeft=pTmp->pRight=NULL;

	if(p==NULL)
	{
		p=pTmp;
		return;
	}
	if(num<p->num)
		insert(p->pLeft,num);
	else if(num>p->num)
		insert(p->pRight,num);
	else
		return;

}
void PrintInLayer(Node* p)
{
	queue<Node*> MyQueue;
	int MyQueue_size;
	int MyQueue_pos;
	MyQueue.push(p);
	while(p!=NULL||!MyQueue.empty())
	{
		MyQueue_size=MyQueue.size();
		MyQueue_pos=0;
		while(MyQueue_pos<MyQueue_size)
		{
			cout<<p->num<<" ";
			MyQueue.pop();
			if(p->pLeft!=NULL)
				MyQueue.push(p->pLeft);
			if (p->pRight!=NULL)
				MyQueue.push(p->pRight);
			if(!MyQueue.empty())
			{
				p=MyQueue.front();
				//MyQueue.pop();
			}
			else
			p=NULL;
			MyQueue_pos++;
		}
		cout<<endl;
	
	}
}
void main()
{
	Node* p=NULL;
	insert(p,10);
	insert(p,6);
	insert(p,14);
	insert(p,4);
	insert(p,8);
	insert(p,12);
	insert(p,16);
	insert(p,1);
	insert(p,5);
	insert(p,15);
	insert(p,17);
	insert(p,7);
	insert(p,9);
        PrintInLayer(p);
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值