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