#include
#include
#include
#include
#define MAX 50
//链式二叉树结构
typedef struct Btree
{
char cData;
struct Btree *pLchild;
struct Btree *pRchild;
}BTree;
//静态队列,实现二叉树层次遍历
typedef struct Queue
{
BTree queData[MAX];
int front;
int rear;
}QueueNode;
//构造空二叉树
BTree *InitBtree()
{
BTree *root;
root= NULL;
return root;
}
//构造空队列
QueueNode *InitQueue()
{
QueueNode *queue;
queue= (QueueNode *)malloc( sizeof(QueueNode) );
queue->front= queue->rear= 0;
return queue;
}
//建立二叉树,先序遍历输入各节点
void CreateBtree(BTree **root)
{
char c;
c= getchar();
if ( c == '.' ) //输入'.'则表示节点为空
{
*root=NULL;
}
else
{
*root= (BTree *)malloc( sizeof(BTree) );
(*root)->cData= c;
CreateBtree( &((*root)->pLchild) );
CreateBtree( &((*root)->pRchild) );
}
}
//入队操作
int Push(QueueNode *s, BTree *Bnode)
{
//判断队列是否满
if ( (s->rear+1)%MAX == s->front )
{
printf("Queue full!/n");
return 0;
}
else
{
s->queData[s->rear]= *Bnode;
s->rear= ( s->rear+1 )%MAX;
return 1;
}
}
//出队操作
int Pop(QueueNode *s)
{
//判断队列是否以为空
if ( s->front == s->rear )
{
printf("Queue null!/n");
return 0;
}
else
{
s->front= ( s->front+1 )%MAX;
return 1;
}
}
//读队列头元素
BTree *GetFront(QueueNode *s)
{
//判断队列是否以为空
if ( s->front == s->rear )
{
printf("Stack null!/n");
return 0;
}
else
{
return &( s->queData[s->front] );
}
}
//判断队列是否为空
int IsEmptyQueue(QueueNode *q)
{
if ( q->front == q->rear )
{
return 1;
}
else
{
return 0;
}
}
main()
{
BTree *Broot; //储存整棵二叉树
BTree *node; //读取队列元素的暂存变量
QueueNode *Queue;
Broot= InitBtree();
Queue= InitQueue();
//建立二叉树
CreateBtree(&Broot);
Push(Queue,Broot);
//清屏
//clrscr();
//层次遍历输出二叉树的实现
while( !IsEmptyQueue(Queue) )
{
node= GetFront(Queue);
printf("%c",node->cData);
if ( node->pLchild!= NULL )
{
Push( Queue,node->pLchild );
}
if ( node->pRchild!= NULL )
{
Push( Queue,node->pRchild );
}
Pop(Queue);
}
print("/n");
}