二叉樹的一些操作_第1頁
二叉樹的一些操作_第2頁
二叉樹的一些操作_第3頁
二叉樹的一些操作_第4頁
二叉樹的一些操作_第5頁
已閱讀5頁,還剩4頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

1、#include #include #include #define OVERFLOW 0#define OK 1#define NULL 0#define Max 100typedef int Status ;typedef char TElemType;typedef struct BiTNode / 結(jié)點(diǎn)結(jié)構(gòu)TElemType data;struct BiTNode *lchild, *rchild;/ 左右孩子指針 BiTNode, *BiTree;Status CreateBiTree (BiTree &T)char ch; scanf(%c,&ch) ;if(ch=#)T=NULL

2、;elseif(!(T=(BiTNode *)malloc(sizeof(BiTNode)exit(OVERFLOW);/生成根結(jié)點(diǎn)/構(gòu)造左子樹/生成根結(jié)點(diǎn)/構(gòu)造左子樹/構(gòu)造右子樹CreateBiTree( T-lchild);CreateBiTree( T-rchild);return OK; / CreateBiTreevoid Preorder (BiTree T) / 先序遍歷二叉樹if (T) printf(%c,T-data); / 訪問結(jié)點(diǎn)Preorder(T-lchild); / 遍歷左子樹Preorder(T-rchild);/ 遍歷右子樹typedef structBiTr

3、ee stackMax;int top; SqStack;void Initstack(SqStack *s) / s=(SqStack *)malloc(Max*sizeof(elemtype); s-top=-1;int EmptyStack(SqStack s)if (s.top=-1) return 1;else return 0;void push(SqStack *s,BiTree e)(*s).top+;(*s).stack(*s).top=e;BiTree pop(SqStack *s)BiTree x;x=s-stacks-top;s-top-;return x;Status

4、 InorderTraverse(BiTree T)BiTree p;SqStack S;Initstack(&S);p=T;while(p|!EmptyStack(S)while (p)push(&S,p);p=p-lchild;if(!EmptyStack(S)p=pop(&S);printf(%c,p-data);p=p-rchild;return OK;void Postreorder (BiTree T) / 后序遍歷二叉樹if (T) Postreorder(T-lchild);/ 遍歷左子樹Postreorder(T-rchild);/ 遍歷右子樹printf(%c,T-data

5、); / 訪問結(jié)點(diǎn)void CountLeaf (BiTree T, int& count)if ( T ) if (!T-lchild)& (!T-rchild)count+; / 對葉子結(jié)點(diǎn)計(jì)數(shù)CountLeaf( T-lchild, count);CountLeaf( T-rchild, count); / if / CountLeafint Depth (BiTree T ) / 返回二叉樹的深度int depthval,depthLeft,depthRight;if ( !T )depthval = 0;elsedepthLeft = Depth( T-lchild );depthR

6、ight= Depth( T-rchild );depthval = 1 + (depthLeft depthRight ?depthLeft : depthRight); return depthval;int main()int count=0;BiTree q;printf(”請輸入樹,若無孩子結(jié)點(diǎn)用#代替:n);CreateBiTree(q);printf(先序遍歷結(jié)果為:n);Preorder(q);printf(n);printf(沖序遍歷結(jié)果為:n”);InorderTraverse(q);printf(n);printf(”后序遍歷結(jié)果為:n);Postreorder(q);printf(n);CountLeaf(q,count);printf( 葉子節(jié)點(diǎn)個(gè)

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論