#include<stdio.h>
#define maxsize 100
#define NULLData 0
typedef char datatype;
typedef struct Binnode
{
datatype data;
struct BinNode* lchild,*rchild;
}BinNode,*Bintree;
typedef struct seqqueue
{
Bintree data[maxsize];
int front,rear;
}SeqQue,*SeQue;
Bintree CreateTree(Bintree T)
{
char ch;
scanf("%c",&ch);
if(ch=='#')
return 0;
else
{
T=(Bintree)malloc(sizeof(BinNode));
T->data=ch;
T->lchild=CreateTree(T->lchild);
T->rchild=CreateTree(T->rchild);
}
return T;
}
void InitQue(SeQue Q)
{
Q->front=Q->rear=0;
}
int EmptyQue(SeQue Q)
{
if(Q->front==Q->rear)
return 1;
else
return 0;
}
int EnQue(SeQue Q,Bintree T)
{
if((Q->rear+1)%maxsize==Q->front)
{
printf("队列已满!\n");
return 0;
}
else
{
Q->rear=(Q->rear+1)%maxsize;
Q->data[Q->rear]=T;
return 1;
}
}
int OutQue(SeQue Q)
{
if(EmptyQue(Q))
{
printf("队列空!\n");
return 0;
}
else
{
Q->front=(Q->front+1)%maxsize;
return 1;
}
}
Bintree Gethead(SeQue Q)
{
if(EmptyQue(Q))
return NULLData;
else
return Q->data[(Q->front+1)%maxsize];
}
void Levelorder(Bintree T)
{
Bintree p;
SeqQue Q;
InitQue(&Q);
if(T!=NULL)
{
EnQue(&Q,T);
while(!EmptyQue(&Q))
{
p=Gethead(&Q);
OutQue(&Q);
printf("%c ",p->data);
if(p->lchild!=NULL)
EnQue(&Q,p->lchild);
if(p->rchild!=NULL)
EnQue(&Q,p->rchild);
}
}
}
main()
{
Bintree t;
printf("请按先序的方式输入二叉树的结点元素(注:#表示节点为空):");
t=CreateTree(t);
printf("按层次遍历输出:");
Levelorder(t);
}