#include<stdio.h>
#include<malloc.h>
#define len sizeof(struct BiTNode )
typedef struct BiTNode
{
char data; //数据域
struct BiTNode *lchild; //左孩子指针
struct BiTNode *rchild; //右孩子指针
}BiTNode,*BiTree;
void creat(BiTree &Tree); // 构建二叉树
int countleaf(BiTree Tree); // 求叶子结点个数
int main()
{
BiTree Tree;
creat(Tree); // 创建二叉树
printf("%d\n", countleaf(Tree)); // 输出叶子节点个数
return 0;
}
// 创建二叉树函数实现
void creat(BiTree &Tree)
{
char ch;
scanf("%c", &ch);
if (ch == '#') {
Tree = NULL;
} else {
Tree = (BiTNode*)malloc(len);
Tree->data = ch;
creat(Tree->lchild);
creat(Tree->rchild);
}
}
// 求叶子结点个数函数实现
int countleaf(BiTree Tree)
{
if (Tree == NULL) {
return 0;
} else if (Tree->lchild == NULL && Tree->rchild == NULL) {
return 1;
} else {
return countleaf(Tree->lchild) + countleaf(Tree->rchild);
}
}
在这段代码中,我们通过递归的方式遍历二叉树,当节点为NULL时,表示当前节点为空;当节点的左右孩子都为空时,表示当前节点是叶子节点。通过递归计算左右子树的叶子结点个数,最终得到整棵二叉树的叶子结点个数。
内容由零声教学AI助手提供,问题来源于学员提问