6-1 二叉樹求深度和葉子數 (20 分)
阿新 • • 發佈:2018-12-20
編寫函式計算二叉樹的深度以及葉子節點數。二叉樹採用二叉連結串列儲存結構
函式介面定義:
int GetDepthOfBiTree ( BiTree T); int LeafCount(BiTree T);
其中 T
是使用者傳入的引數,表示二叉樹根節點的地址。函式須返回二叉樹的深度(也稱為高度)。
裁判測試程式樣例:
//標頭檔案包含 #include<stdlib.h> #include<stdio.h> #include<malloc.h> //函式狀態碼定義 #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define OVERFLOW -1 #define INFEASIBLE -2 #define NULL 0 typedef int Status; //二叉連結串列儲存結構定義 typedef int TElemType; typedef struct BiTNode{ TElemType data; struct BiTNode *lchild, *rchild; } BiTNode, *BiTree; //先序建立二叉樹各結點 Status CreateBiTree(BiTree &T){ TElemType e; scanf("%d",&e); if(e==0)T=NULL; else{ T=(BiTree)malloc(sizeof(BiTNode)); if(!T)exit(OVERFLOW); T->data=e; CreateBiTree(T->lchild); CreateBiTree(T->rchild); } return OK; } //下面是需要實現的函式的宣告 int GetDepthOfBiTree ( BiTree T); int LeafCount(BiTree T); //下面是主函式 int main() { BiTree T; int depth, numberOfLeaves; CreateBiTree(T); depth= GetDepthOfBiTree(T); numberOfLeaves=LeafCount(T); printf("%d %d\n",depth,numberOfLeaves); } /* 請在這裡填寫答案 */
輸入樣例:
1 3 0 0 5 7 0 0 0
輸出樣例:
3 2
int GetDepthOfBiTree ( BiTree T) { if(T == NULL) return 0; else{ int lenr = 1 + GetDepthOfBiTree(T->rchild); int lenl = 1 + GetDepthOfBiTree(T->lchild); if(lenr > lenl) return lenr; else return lenl; } } int LeafCount(BiTree T) { if( T == NULL) return 0; else if( T->lchild== NULL || T->rchild == NULL) return 1; else return LeafCount(T->lchild) + LeafCount(T->rchild); }