1. 程式人生 > >1-6 統計二叉樹度為2的結點個數 (10 分)

1-6 統計二叉樹度為2的結點個數 (10 分)

本題要求實現一個函式,可統計二叉樹中度為2的結點個數。

函式介面定義:

int NodeCount ( BiTree T);

T是二叉樹樹根指標,函式NodeCount返回二叉樹中度為2的結點個數,若樹為空,返回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;
}
/* 你的程式碼將被嵌在這裡 */

輸出樣例(對於圖中給出的樹):

二叉樹.png

2
int NodeCount( BiTree T){
if(T==NULL) {
    return 0;
    }
   if(T->lchild==NULL&&T->rchild!=NULL||T->rchild==NULL&&T->lchild!=NULL){
    
    return 2+NodeCount(T->lchild)+NodeCount(T->rchild);
}
return NodeCount(T->lchild)+NodeCount(T->rchild);
}