-->
当前位置:首页 > 题库

函数题:统计二叉树的结点个数

Luz4年前 (2022-09-15)题库469
统计二叉树中的结点个数,按要求输出。

### 函数接口定义:
c++
int NodeCount( BinTree BT ) /*计算二叉树中结点总数*/
int NodeCountN0( BinTree BT ) /*计算二叉树中度为0的结点个数*/
int NodeCountN1( BinTree BT ) /*计算二叉树中度为1的结点个数*/
int NodeCountN2( BinTree BT ) /*计算二叉树中度为2的结点个数*/

其中,BinTree 的结构定义为:
c++
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};


### 裁判测试程序样例:
c++
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100

typedef struct TNode * BinTree; /* 二叉树类型 */
typedef char ElementType;
struct TNode{ /* 树结点定义 */
ElementType Data; /* 结点数据 */
BinTree Left; /* 指向左子树 */
BinTree Right; /* 指向右子树 */
};

int NodeCount( BinTree BT );
int NodeCountN0( BinTree BT );
int NodeCountN1( BinTree BT );
int NodeCountN2( BinTree BT );

//按先序次序输入二叉树中结点的值(一个字符),@表示空树,构造二叉链表表示二叉树T
BinTree CreatBinTree()
{
ElementType ch;
BinTree T;
scanf("%c",&ch); /*按先序次序输入树的结点,空树输入@*/
if(ch == '@')
T = NULL;
else {
T = (BinTree)malloc(sizeof(struct TNode));
T->Data = ch;
T->Left = CreatBinTree();
T->Right = CreatBinTree();
}
return T;
}

int main()
{
BinTree BT;
int count,count0,count1,count2;
BT = CreatBinTree();

if(BT == NULL){
printf("\n空树!\n");
}else{
count = NodeCount(BT);
printf("该二叉树中总结点个数为:%d",count);
printf("\n");

count0 = NodeCountN0(BT) ;
printf("该二叉树中叶子结点个数为:%d",count0);
printf("\n");

count1 = NodeCountN1(BT) ;
printf("该二叉树中度为1的结点个数为:%d",count1);
printf("\n");

count2 = NodeCountN2(BT) ;
printf("该二叉树中度为2的结点个数为:%d",count2);
}
return 0;
}
/* 请在这里填写答案 */


![QQ截图20201126013943.png](~/9961a67b-00e3-402c-90f7-02a9a6b3341c.png)

### 输入样例:
in
ABD@@EG@@@C@F@@


### 输出样例:
out
该二叉树中总结点个数为:7
该二叉树中叶子结点个数为:3
该二叉树中度为1的结点个数为:2
该二叉树中度为2的结点个数为:2









答案:若无答案欢迎评论