二叉树的广度优先遍历(又称层序遍历)需要使用队列(通常用链表实现)来完成。以下是实现的代码,分为三个文件:function.h、queue.cpp 和 main.cpp。
1.function.h
#include<stdio.h>
#include<stdlib.h>
//二叉树的函数声明
typedef char elemtype;
typedef struct bitree {
elemtype tdata;
struct bitree* lchild, * rchild;
}bitree, * pbitree;
typedef struct tag {
pbitree p;//指向某一个二叉树指针
struct tag* next;
}tag, * ptag;
//辅助队列函数声明
typedef struct node{
pbitree data;
struct node *next;
}node;
typedef struct sq_queue {
node* front, * rear;
}sq_queue;
void init_queue(sq_queue& Q);
bool is_empty(sq_queue Q);
void en_queue(sq_queue &Q,pbitree x);
void de_queue(sq_queue &Q, pbitree &keep);
2.queue.cpp(辅助队列的实现)
#include"function.h"
void init_queue(sq_queue& Q)
{
Q.front = Q.rear = (node*)calloc(1, sizeof(node));
Q.front->next = NULL;
}
bool is_empty(sq_queue Q)
{
if (Q.rear == Q.front)
{
return true;
}
return false;
}
void en_queue(sq_queue &Q,pbitree x)
{
node* s = (node*)calloc(1, sizeof(node));
s->data = x;
s->next = NULL;
Q.rear->next = s;
Q.rear = s;
}
void de_queue(sq_queue& Q, pbitree& keep)
{
node* p = Q.front->next;
keep = p->data;
Q.front->next = p->next;
if (Q.rear == p)
{
Q.rear = Q.front;
}
free(p);
}
3.main.cpp(层序遍历的实现)
#include"function.h"
void level_order(pbitree tree)
{
sq_queue Q;
init_queue(Q);
pbitree keep;
en_queue(Q, tree);//将根节点入队
while (!is_empty(Q))
{
de_queue(Q,keep);
putchar(keep->tdata);
if (keep->lchild != NULL)
{
en_queue(Q, keep->lchild);//将左孩子入队
}
if (keep->rchild != NULL)
{
en_queue(Q, keep->rchild);//将右孩子入队
}
}
}
int main()
{
//二叉树建树
pbitree pnew;
pbitree tree = NULL;
elemtype c;
ptag head = NULL, tail = NULL, pcur = NULL, link_new = NULL;
while (scanf("%c", &c))
{
if (c == '\n')
{
break;
}
pnew = (pbitree)calloc(1, sizeof(bitree));
pnew->tdata = c;
link_new = (ptag)calloc(1, sizeof(tag));
link_new->p = pnew;
if (tree == NULL)
{
tree = pnew;
head = link_new; tail = link_new;
pcur = link_new; link_new = link_new;
continue;
}
else
{
tail->next = link_new;
tail = tail->next;
}
if (pcur->p->lchild == NULL)
{
pcur->p->lchild = pnew;
}
else if(pcur->p->rchild == NULL)
{
pcur->p->rchild = pnew;
pcur = pcur->next;
}
}
level_order(tree);//层序遍历(广度优先遍历)
}