/************************************************************************/
/* 二叉树广度优先遍历 */
/************************************************************************/
#include <stdio.h>
#include <STDLIB.H>
#define _OK 1
#define _ERROR 0
//定义二叉树节点中的元素类型
typedef char Element;
//二叉树的抽象
typedef struct BiTNode{
Element data;
struct BiTNode *lchild,*rchild;//定义左右子树
}BiTNode,*BiTree;
//定义队列节点中的元素类型(这里队列节点中的元素类型是二叉树节点指针)
typedef BiTNode *QElementType;
typedef int status;
/*****************************************************
使用广度优先遍历要使用到队列,队列相关操作
******************************************************/
typedef struct QNode
{
QElementType data;
struct QNode *next;//下一个节点
} QNode,*QueuePtr;
/*队列的数据抽象*/
typedef struct
{
QueuePtr front;//队首指针(出队)[指向准出队元素]
QueuePtr rear;//队尾指针(入队)[指向刚入队元素]
}LinkQueue;
/*队列的初始化*/
status InitQueue(LinkQueue &Q)
{
Q.front = NULL;
Q.rear = NULL;
return _OK;
}
/*判断队列是为空*/
bool IsEmpty(LinkQueue Q)
{
return Q.front == NULL;
}
/*入队*/
status InQueue(LinkQueue &Q,QElementType e)
{
//构造节点
QNode *ptrNode =(QNode*) malloc(sizeof(QNode));
if(!ptrNode)
return _ERROR;
ptrNode->data=e;
ptrNode->next=NULL;
if(IsEmpty(Q))//判断队列是否为空
{
Q.front=Q.rear=ptrNode;
return _OK;
}
//如果不为空
Q.rear->next=ptrNode;
Q.rear = ptrNode;
return _OK;
}
/*出队*/
status OutQueue(LinkQueue &Q,QElementType &e)
{
if(IsEmpty(Q))
return _ERROR;
QNode *tempPtr = Q.front;
e=tempPtr->data;
Q.front = tempPtr->next;
free(tempPtr);
return _OK;
}
/************************队列操作结束******************************/
/************************************************************************/
/* 二叉树相关操作 */
/************************************************************************/
//创建二叉树
int CreateBiTree(BiTree &T)
{
char ch;
printf("请输入:\n");
scanf("%s",&ch);
if(ch=='#')
T = NULL;
else
{
//为新节点分配空间
if(!(T = (BiTNode*)malloc(sizeof(BiTNode))))
return 0;//分配失败
T->data = ch;
//创建左子树
CreateBiTree(T->lchild);
//创建右子树
CreateBiTree(T->rchild);
}
return 1;
}
//访问树节点中的元素
void VisitBTNode(BiTNode *BT)
{
printf("%c \n",BT->data);
}
//访问队列中的元素
void VisitQNode(QNode *Q)
{
VisitBTNode(Q->data);
}
/*广度优先遍历*/
void leverOrder(BiTree T)
{
QElementType e;
LinkQueue Q;//定义队列Q为LinkQueue类型
InitQueue(Q);
InQueue(Q,T);//根节点入队
while (!IsEmpty(Q))//如果队列非空
{
VisitQNode(Q.front);
if(Q.front->data->lchild!=NULL)
InQueue(Q,Q.front->data->lchild);
if(Q.front->data->rchild!=NULL)
InQueue(Q,Q.front->data->rchild);
OutQueue(Q,e);
}
}
void main()
{
BiTree T;
CreateBiTree(T);
leverOrder(T);
}