层序遍历树,输出遍历结果
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 100
typedef struct BiTNode{ //树的节点
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
typedef struct{ //队列存储树节点
int front, rear;
BiTNode * data[MAX];
} Queue;
void initQueue (Queue *q) //初始化队列
{
q->rear=0;
q->front=0;
}
int EmptyQueue(Queue *q) //判断队列是否为空
{
if(q->rear==q->front)
return 1;
else
return 0;
}
BiTNode * DeQueue(Queue *q) //队尾删除一个元素
{
return q->data[(q->front)++];
}
void InQueue(Queue *q,BiTNode * p) //队头一个元素
{
if (q->rear==MAX)
{
printf("队列已满!");
}
else
q->data[(q->rear)++]=p;
}
BiTree Create(BiTree T) //创建二叉树 ,这里使用“#”符号进行分隔
{
char ch;
ch=getchar();
if(ch=='#')
T=NULL;
else
{
if(!(T=(BiTNode *)malloc(sizeof(BiTNode))))
printf("Error!");
T->data=ch;
T->lchild=Create(T->lchild); //递归创建
T->rchild=Create(T->rchild);
}
return T;
}
Travel (BiTree T,Queue *q) //层序遍历
{
BiTNode *p;
p=T;
if(p!=NULL)
InQueue(q,p);
while(!EmptyQueue(q))
{
p=DeQueue(q);
printf("%c",p->data);
if(p->lchild!=NULL)
InQueue(q,p->lchild);
if(p->rchild!=NULL)
InQueue(q,p->rchild);
}
}
main()
{
BiTree T;
Queue q;
initQueue(&q);
T=Create(T);
Travel(T,&q);
printf("\n");
}
测试用例及结果:
注意输入的格式,由于创建树时采用的是递归创建,所以当从左子树跳到右子树要使用#符号跳出一层递归