主要思想:
从根结点开始逐层逐个地访问各个结点。在周游开始的时候,首先把根结点放入队列;
然后每次从队列中取出队头元素进行处理,每处理一个结点时,按从左到右的顺序把它的所有子结点放入对列。
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 20
#define OK 1
#define ERROR 0
typedef int Status;
typedef char TElemType;
//二叉树的链式储存结构
typedef struct BiTNode
{
TElemType data;
struct BiTNode * lchild;
struct BiTNode * rchild;
}BiTNode,*BiTree;
typedef BiTree QElemtype;
//循环队列的储存结构
typedef struct
{
QElemtype data[MAXSIZE];
int front;
int rear;
}sqQueue;
//队列的初始化
Status InitQueue(sqQueue * Q)
{
Q->front=0;
Q->rear=0;
return OK;
}
//队列长度
Status QueueLength(sqQueue Q)
{
return (Q.rear-Q.front+MAXSIZE)%MAXSIZE;
}
//入队操作
Status EnQueue(sqQueue * Q, QElemtype e)
{
if((Q->rear+1)%MAXSIZE==Q->front)
{
return ERROR;
}
Q->data[Q->rear]=e;
Q->rear=(Q->rear+1)%MAXSIZE;
return OK;
}
//出队操作
Status DeQueue(sqQueue * Q,QElemtype * e)
{
if(Q->front==Q->rear)
{
return ERROR;
}
*e=Q->data[Q->front];
Q->front=(Q->front+1)%MAXSIZE;
return OK;
}
//二叉树的建立
void CreateBiTree(BiTree * T)
{
TElemType ch;
scanf("%c",&ch);
if(ch=='#')
{
*T=NULL;
}
else
{
*T=(BiTree)malloc(sizeof(BiTNode));
}
if(!*T)
{
return ;
}
else
{
(*T)->data=ch;
CreateBiTree(&(*T)->lchild); //构造左子树
CreateBiTree(&(*T)->rchild); //构造右子树
}
}
//广度优先周游二叉树(层次遍历)
void LevelOrder(BiTree * T,sqQueue * Q)
{
if(*T)
{
EnQueue(Q,(*T));
}
while(QueueLength((*Q))!=0)
{
DeQueue(Q,&(*T));
printf("%c ",(*T)->data); //访问当前结点
if((*T)->lchild!=NULL)
{
EnQueue(Q,(*T)->lchild);
}
if((*T)->rchild!=NULL)
{
EnQueue(Q,(*T)->rchild);
}
}
printf("\n");
}
int main()
{
sqQueue Q;
BiTree root;
InitQueue(&Q);
printf("please enter the data:\n");
CreateBiTree(&root);
printf("LevelOrdertraversal the data:\n");
LevelOrder(&root,&Q);
return 0;
}