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)
return 0;
else
return NodeCountOfBiTree(T->lchild)+NodeCountOfBiTree(T->rchild)+1; //+根节点
}
/* [1]
/ \
/ \
[3] [5]
/
/
[3] */