二叉树的遍历在之前写过的递归和非递归的形式都是通过访问一个子树在访问结点来完成的,有时候我们需要对树进行一层一层的遍历,这样就的遍历叫做层次遍历。
实现二叉树的层次遍历可以借助一个队列来进行实现,我们访问根结点,把它放入队列,如果队列中现在不为空,那么就把这个结点出队列,并且输出结点,在把它的左孩子结点和右孩子结点入队列。就这样进行循环直到队列为空停止,此时输出的结点就是层次遍历的顺序。
代码通过链式队列的辅助来实现:
#include<cstdio>
#include<malloc.h>
using namespace std;
typedef struct TREE
{
char data;
TREE *lchild,*rchild;
} TREE, *tree; //定义树结点结构
typedef struct node
{
tree ch;
node *next;
} node,*nodelist; //定义队列结点结构
typedef struct
{
nodelist front;
nodelist rear;
} linkqueue; //定义队列指针
//建树
tree createtree()
{
char ch;
tree T;
scanf("%c",&ch);
if(ch=='#')
T=NULL;
else
{
T=(tree)malloc(sizeof(TREE));
T->data=ch;
T->lchild = createtree();
T->rchild = createtree();
}
return T;
}
//初始化一个带头结点的队列
void initqueue(linkqueue &q)
{
q.front=q.rear=(nodelist)malloc(sizeof(node));
q.front->next=NULL;
}
//入队列
void enqueue(linkqueue &q,tree p)
{
nodelist s;
int first=1;
s=(nodelist)malloc(sizeof(node));
s->ch=p;
s->next=NULL;
q.rear->next=s;
q.rear=s;
}
//出队列
void dequeue(linkqueue &q,tree &p)
{
char data;
nodelist s;
s=q.front->next;
p=s->ch;
data=p->data;
q.front->next=s->next;
if(q.rear==s)
q.rear=q.front;
free(s);
printf("%c ",data);
}
//判断队列是否为空
int queueempty(linkqueue q)
{
if(q.front->next==NULL)
return 1;
return 0;
}
//按层次遍历树中结点
void traverse(tree bt)
{
linkqueue q;
tree p;
initqueue(q);
p=bt;
enqueue(q,p);
while(queueempty(q)!=1)
{
dequeue(q,p);
if(p->lchild!=NULL)
enqueue(q,p->lchild);
if(p->rchild!=NULL)
enqueue(q,p->rchild);
}
printf("\n");
}
//主函数
int main()
{
freopen("1.txt", "r", stdin);
tree bt;
bt = createtree();
printf("按层次遍历树中结点其输出顺序为: \n");
traverse(bt);
}