规则:
- 判断树是否为空,为空则返回;
- 若不空,从树的第一层。也就是根节点开始访问。
- 从上而下逐层遍历, 在同一层中,按从左到右的顺序对节点逐个访问。
#include<stdio.h>
#include<stdlib.h>
typedef struct tree{
char date;
struct tree*pLeft,*pRight;
}TREE,*PTREE;
typedef struct List{
PTREE pBit;
struct List *pNext;
}NODE,*PNODE;
typedef struct queue{
PNODE front;
PNODE rear;
}QUEUE,*PQUEUE;
void init_queue(PQUEUE); /*初始化队列*/
void en_queue(PQUEUE,PTREE); /*入队操作*/
PTREE out_queue(PQUEUE); /*出队操作*/
void creat_tree(PTREE*); /*利用先序遍历的方式创建二叉树*/
void traverse_tree(PTREE); /*实现树的层序遍历*/
int main (void)
{
PTREE pT = NULL;
creat_tree(&pT);
traverse_tree(pT);
return 0;
}
void init_queue(PQUEUE pQ)
{
pQ->rear = pQ->front = (PNODE)malloc(sizeof(NODE));
if(pQ->front == NULL)
exit(0);
pQ->front->pNext = NULL;
return;
}
void en_queue(PQUEUE pQ,PTREE pT)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if(pNew == NULL)
exit(0);
else
{
pNew->pBit = pT;
pNew->pNext = NULL;
pQ->rear->pNext = pNew;
pQ->rear = pNew;
return;
}
}
PTREE out_queue(PQUEUE pQ)
{
PNODE p = pQ->front->pNext;
if(pQ->front == pQ->rear)
return NULL;
pQ->front->pNext = p->pNext;
if(pQ->rear == p)
pQ->rear = pQ->front;
return p->pBit;
}
void creat_tree(PTREE *pT)
{
char a;
scanf("%c",&a);
if(a == '#')
*pT = NULL;
else
{
(*pT) = (PTREE)malloc(sizeof(TREE));
if((*pT) == NULL)
exit(0);
(*pT)->date = a;
creat_tree(&(*pT)->pLeft);
creat_tree(&(*pT)->pRight);
return;
}
}
void traverse_tree(PTREE pT)
{
PTREE t = NULL;
QUEUE pQ;
init_queue(&pQ);
if(pT != NULL)
en_queue(&pQ,pT); /*若树不空,让根节点入队*/
else
return;
while(pQ.front != pQ.rear) /*队列不空*/
{
t = out_queue(&pQ); /*让队列中元素出队*/
printf("%c\t",t->date);
if(t->pLeft != NULL) /*判断左子树是否为空*/
en_queue(&pQ,t->pLeft); /*不空则让它入队*/
if(t->pRight != NULL) /*判断右子树是否为空*/
en_queue(&pQ,t->pRight); /*不空则让它入队*/
}
printf("\n");
return;
}