資源描述:
《建立二叉樹與層次遍歷二叉樹程序》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫。
1、#include/*I/O函數(shù)*/#include"conio.h"#include"stdlib.h"#defineQUEUESIZE100/*隊列初始容量*/#defineTRUE1#defineFALSE!TRUE#defineStatuint#defineBitTreeElementTypeint#defineSHUJU"%d"#defineEND-1typedefstructBitnode/*樹的鏈?zhǔn)酱鎯?/{BitTreeElementTypedata;structBitnode*lchild;/*左孩子*/structBi
2、tnode*rchild;/*右孩子*/}BTnode,*BitTree;typedefBitTreeQueueElemtype;typedefstruct/*定義數(shù)據(jù)結(jié)構(gòu)*/{QueueElemtypedata[QUEUESIZE];intfront;/*隊列的頭指針*/intrear;/*隊列的尾指針*/}queue;intCreateQueue(queue*q);/*創(chuàng)建隊列*/intEnQueue(queue*q,QueueElemtypec);/*向隊尾插入元素c*/StatuDeQueue(queue*q,QueueElemtype*reb)
3、;/*隊頭元素出隊用reb返回其值*/StatuCreateBitTree(BitTree*T);/*初始化二叉樹*/StatuLayerTravelBitTree(BitTreeT);/*層次遍歷二叉樹*/StatuVisitData(BitTreeElementTypedata);voidmain(){BitTreet;printf("Inputdatatocreatebittreeand'");printf(SHUJU,END);printf("'willmakenulltree.");/*輸入根結(jié)點*/CreateBitTree(&t);/*
4、初始化二叉樹*/printf("Layerordertravelthetree:");/*層次遍歷二叉樹*/LayerTravelBitTree(t);/*層次遍歷二叉樹*/}StatuCreateBitTree(BitTree*T)/*初始化二叉樹*/{BitTreeElementTypeinputdata;*T=(BitTree)malloc(sizeof(BTnode));printf("EnterData:");/*輸入數(shù)據(jù)*/fflush(stdin);scanf(SHUJU,&inputdata);if(inputdata==END){T
5、=NULL;returnFALSE;}else{(*T)->data=inputdata;/*將輸入的數(shù)據(jù)存入結(jié)點*/printf("Createleftsubtree...<");CreateBitTree(&((*T)->lchild));/*遞歸循環(huán)輸入左子樹*/printf("Createrightsubtree...<");CreateBitTree(&((*T)->rchild));/*遞歸循環(huán)輸入右子樹*/returnTRUE;}}StatuLayerTravelBitTree(BitTreeT)/*層次遍歷二叉樹*/{queuetq;/*
6、隊列tq*/QueueElemtyperes;/*用來返回對頭元素*/CreateQueue(&tq);/*創(chuàng)建隊列*/EnQueue(&tq,T);/*將T插入隊尾*/while(DeQueue(&tq,&res)==TRUE)/*當(dāng)隊頭元素不空時執(zhí)行while循環(huán)*/{if(res){;/*訪問隊頭元素*/if(res->lchild->data!=-1)EnQueue(&tq,res->lchild);/*將結(jié)點左孩子插入隊尾*/VisitData(res->data);if(res->rchild->data!=-1)EnQueue(&tq,re
7、s->rchild);/*將結(jié)點右孩子插入隊尾*/}}returnTRUE;}intCreateQueue(queue*q){q->front=-1;q->rear=-1;returnTRUE;}intEnQueue(queue*q,QueueElemtypec)/*將元素c插入隊尾*/{q->rear++;/*尾指針加1*/if(q->rear>=QUEUESIZE)/*若尾指針超出隊列長度則提示錯誤*/{printf("Queueoverflow!");exit(0);}q->data[q->rear]=c;return1;}StatuDeQue
8、ue(queue*q,QueueElemtype*ret)/*隊頭元素出隊并用r