按層次遍歷的原則是先被訪問的結點的左右兒子結點也先被訪問,因此需引入先進先出的隊列作為輔助工具。
算法思想為:
(1)將二叉樹根入隊列;
(2)循環直到隊列為空
(2.1)將隊頭元素出隊列,
(2.2)訪問結點數據域,
(2.3)判斷此元素是否有左右孩子,若有,則將它的左右孩子依次入隊,否則轉(2);
#include <iostream> #include <cstdio> #include <malloc.h> using namespace std; #define MAXSIZE 100 typedef char DataType; typedef struct BiTnode { DataType data; struct BiTnode *lchild,*rchild; }BiTNode,*BiTree; typedef struct SQueue { BiTree data[MAXSIZE]; int front,rear; }SQueue,*Queue; BiTree creatTree(BiTree root) { DataType ch; root=(BiTree)malloc(sizeof(BiTNode)); scanf("%c",&ch); if(ch=='#') return 0; root->data=ch; root->lchild=creatTree(root->lchild); root->rchild=creatTree(root->rchild); return root; } void InitQueue(Queue Q) { Q->front=Q->rear=0; } int IsEmptyQueue(Queue Q) { return Q->rear==Q->front?1:0; } void EnQueue(BiTree root,Queue Q) { if((Q->rear+1)%MAXSIZE==Q->front) { printf("Queue is fulled!\n"); return ; } Q->rear=(Q->rear+1)%MAXSIZE; Q->data[Q->rear]=root; } BiTree Gethead(Queue Q) { if(IsEmptyQueue(Q)) return 0; BiTree root; root=Q->data[(Q->front+1)%MAXSIZE]; Q->front=(Q->front+1)%MAXSIZE; return root; } void LevelOrder(BiTree root) { SQueue Q; BiTree t; if(!root) return ; InitQueue(&Q); EnQueue(root,&Q); while(!IsEmptyQueue(&Q)) { t=Gethead(&Q); printf("%c ",t->data); if(t->lchild!=NULL) EnQueue(t->lchild,&Q); if(t->rchild!=NULL) EnQueue(t->rchild,&Q); } } int main() { BiTree tree; tree=creatTree(tree); LevelOrder(tree); return 0; }