編寫函數計算二叉樹的深度以及葉子節點數。二叉樹采用二叉鏈表存儲結構
函數接口定義:
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); }