#define CHAR /* 字元型 */#include <stdio.h> /* EOF(=^Z或F6),NULL */#include <stdlib.h>#include<math.h> /* floor(),ceil(),abs() */#define TRUE 1#define FALSE 0#define OK 1#define ERROR 0typedef int Status; /* Status是函數的類型,其值是函數結果狀態碼,如OK等 */#ifdef CHARtypedef char TElemType;TElemType Nil=' '; /* 字元型以空格符為空白 */#endif#ifdef INTtypedef int TElemType;TElemType Nil=0; /* 整型以0為空白 */#endiftypedef struct BiTNode{TElemType data;struct BiTNode *lchild,*rchild; /* 左右孩子指標 */}BiTNode,*BiTree;typedef BiTree QElemType; /* 設隊列元素為二叉樹的指標類型 */typedef struct QNode//隊列節點結構體{QElemType data;struct QNode *next;}QNode,*QueuePtr;typedef struct //隊列{QueuePtr front,rear; /* 隊頭、隊尾指標 */}LinkQueue;Status InitBiTree(BiTree *T){ /* 操作結果: 構造空二叉樹T */*T=NULL;return OK;}void CreateBiTree(BiTree *T){TElemType ch;#ifdef CHARscanf("%c",&ch);#endif#ifdef INTscanf("%d",&ch);#endifif(ch==Nil) /* 空 */*T=NULL;else{*T=(BiTree)malloc(sizeof(BiTNode));if(!*T)exit(OVERFLOW);(*T)->data=ch; /* 產生根結點 */CreateBiTree(&(*T)->lchild); /* 構造左子樹 */CreateBiTree(&(*T)->rchild); /* 構造右子樹 */}}Status InitQueue(LinkQueue *Q){ /* 構造一個空隊列Q */(*Q).front=(*Q).rear=(QueuePtr)malloc(sizeof(QNode));if(!(*Q).front)exit(OVERFLOW);(*Q).front->next=NULL;return OK;}Status QueueEmpty(LinkQueue Q){ /* 若Q為空白隊列,則返回TRUE,否則返回FALSE */if(Q.front==Q.rear)return TRUE;elsereturn FALSE;}Status EnQueue(LinkQueue *Q,QElemType e){ /* 插入元素e為Q的新的隊尾元素 */QueuePtr p=(QueuePtr)malloc(sizeof(QNode));if(!p) /* 儲存分配失敗 */exit(OVERFLOW);p->data=e;p->next=NULL;(*Q).rear->next=p;(*Q).rear=p;return OK;}Status DeQueue(LinkQueue *Q,QElemType *e){ /* 若隊列不空,刪除Q的隊頭元素,用e返回其值,並返回OK,否則返回ERROR */QueuePtr p;if((*Q).front==(*Q).rear)return ERROR;p=(*Q).front->next;*e=p->data;(*Q).front->next=p->next;if((*Q).rear==p)(*Q).rear=(*Q).front;free(p);return OK;}void LevelOrderTraverse(BiTree T,Status(*Visit)(TElemType)){ /* 初始條件:二叉樹T存在,Visit是對結點操作的應用函數 *//* 操作結果:層序遞迴遍曆T(利用隊列),對每個結點調用函數Visit一次且僅一次 */LinkQueue q;QElemType a;if(T){InitQueue(&q);EnQueue(&q,T);while(!QueueEmpty(q)){DeQueue(&q,&a);Visit(a->data);if(a->lchild!=NULL)EnQueue(&q,a->lchild);if(a->rchild!=NULL)EnQueue(&q,a->rchild);}printf("\n");}}Status visitT(TElemType e){#ifdef CHARprintf("%c ",e);#endif#ifdef INTprintf("%d ",e);#endifreturn OK;}void main(){BiTree T;InitBiTree(&T);#ifdef CHARprintf("請先序輸入二叉樹(如:ab三個空格表示a為根結點,b為左子樹的二叉樹)\n");#endif#ifdef INTprintf("請先序輸入二叉樹(如:1 2 0 0 0表示1為根結點,2為左子樹的二叉樹)\n");#endifCreateBiTree(&T);printf("層次遍曆二叉樹:\n");LevelOrderTraverse(T,visitT);}