6-2 統計二叉樹葉子結點個數 (10 分)
本題要求實現一個函數,可統計二叉樹的葉子結點個數。
函數接口定義:
int LeafCount ( BiTree T);
T是二叉樹樹根指針,函數LeafCount返回二叉樹中葉子結點個數,若樹為空,則返回0。
裁判測試程序樣例:
#include <stdio.h>
#include <stdlib.h>
typedef char ElemType;
typedef struct BiTNode
{
ElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
BiTree Create();/* 細節在此不表 */
int LeafCount ( BiTree T);
int main()
{
BiTree T = Create();
printf("%d\n", LeafCount(T));
return 0;
}
/* 你的代碼將被嵌在這里 */
輸出樣例(對於圖中給出的樹):
3
int LeafCount ( BiTree T){ if(T==NULL) return 0; if(T->lchild==NULL&&T->rchild==NULL){ return 1; } else return LeafCount(T->lchild)+LeafCount(T->rchild); }