您的位置:首页 > 其它

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

2013-09-13 22:10 211 查看
按层遍历二叉树的思路:

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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: