編寫函數計算二叉樹的深度以及葉子節點數。二叉樹采用二叉鏈表存儲結構
函數接口定義:
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;
//創建二叉樹各結點,輸入零代表創建空樹
//采用遞歸的思想創建
//遞歸邊界:空樹如何創建呢:直接輸入0;
//遞歸關系:非空樹的創建問題,可以歸結為先創建根節點,輸入其數據域值;再創建左子樹;最后創建右子樹。左右子樹遞歸即可完成創建!
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
結尾無空行
ANSWER
int GetDepthOfBiTree ( BiTree T){
if(T == NULL)
return 0;//空樹返回0
else{
int m = 0;
int n = 0;
m = GetDepthOfBiTree(T->lchild);
n = GetDepthOfBiTree(T->rchild);
if(m > n)
return m+1;//加根節點
else
return n+1;
}
}
int LeafCount(BiTree T){
if(T == NULL)
return 0;
if(T->lchild == NULL && T->rchild == NULL)
return 1;//如果是葉子結點返回1
else
return LeafCount(T->lchild)+LeafCount(T->rchild);
}