6-2 二叉樹求結點數 (15 分)
編寫函數計算二叉樹中的節點個數。二叉樹采用二叉鏈表存儲結構。
函數接口定義:
int NodeCountOfBiTree ( 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
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 NodeCountOfBiTree ( BiTree T);
//下面是主函數
int main()
{
BiTree T;
int n;
CreateBiTree(T); //先序遞歸創建二叉樹
n= NodeCountOfBiTree(T);
printf("%d",n);
return 0;
}
/* 請在這里填寫答案 */
輸入樣例(注意輸入0代表空子樹):
1 3 0 0 5 3 0 0 0
輸出樣例:
4
int NodeCountOfBiTree ( BiTree T)
{
if(T == NULL)
return 0;
else
return 1 + NodeCountOfBiTree(T->lchild) + NodeCountOfBiTree(T->rchild);
}
