#include <stdio.h>
#include <stdlib.h>
#define MAXQSIZE 100
typedef struct BiTNode
{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
typedef struct
{
BiTree data[MAXQSIZE];
int front;
int rear;
}SeQueue;
int InitQueue(SeQueue *q)
{
q->front=0;
q->rear=0;
return 1;
}
int Push(SeQueue *q,BiTree x)
{
if((q->rear+1)%MAXQSIZE==q->front) return 0;
q->data[q->rear]=x;
q->rear=(q->rear+1)%MAXQSIZE;
return 1;
}
int Pop(SeQueue *q,BiTree *x)
{
if(q->rear==q->front) return 0;
*x=q->data[q->front];
q->front=(q->front+1)%MAXQSIZE;
return 1;
}
int EmptyQueue(SeQueue *q)
{
if(q->rear==q->front) return 1;
else return 0;
}
void CreateBiTree(BiTree *t)
{
char ch;
scanf("%c",&ch);
if(ch=='@') *t=NULL;
else
{
*t=(BiTNode *)malloc(sizeof(BiTNode));
(*t)->data=ch;
CreateBiTree(&(*t)->lchild);
CreateBiTree(&(*t)->rchild);
}
}
void level_order_traverse(BiTree t)
{
SeQueue q;
InitQueue(&q);
BiTree p;
if(t)
{
Push(&q,t);
while(!EmptyQueue(&q))
{
Pop(&q,&p);
printf("%c",p->data);
if(p->lchild) Push(&q,p->lchild);
if(p->rchild) Push(&q,p->rchild);
}
}
}
int main()
{
BiTree t;
CreateBiTree(&t);
level_order_traverse(t);
return 0;
}
注意队列储存数据的数组用BiTree data[MAXQSIZE];