C语言统计二叉树中叶子结点的个数
时间: 2024-12-21 17:29:47 浏览: 64
在C语言中,统计二叉树中叶子节点的数量通常需要遍历整棵树。对于每个节点,我们可以检查它是否有左孩子和右孩子。如果没有,则它是叶子节点。下面是一个简单的递归方法:
```c
#include <stdio.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
int countLeaves(TreeNode* root) {
// 如果根节点为空,返回0
if (root == NULL)
return 0;
// 如果根节点没有左右子节点,它是叶子节点,计数加1
else if (root->left == NULL && root->right == NULL)
return 1;
// 否则,对左子树和右子树分别递归计数,然后相加
else
return countLeaves(root->left) + countLeaves(root->right);
}
```
这个`countLeaves`函数会返回给定二叉树中叶子节点的数量。你可以通过传入二叉树的根节点来调用它。
相关问题
c语言统计二叉树中结点的个数
统计二叉树中结点的个数可以使用递归的方法进行求解,具体实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结点结构体
typedef struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 创建二叉树
TreeNode* createBinaryTree() {
int data;
scanf("%d", &data);
if (data == -1) {
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->data = data;
root->left = createBinaryTree();
root->right = createBinaryTree();
return root;
}
// 统计二叉树中结点的个数
int countNodes(TreeNode* root) {
if (root == NULL) {
return 0;
}
return 1 + countNodes(root->left) + countNodes(root->right);
}
int main() {
printf("请输入二叉树的结点(-1表示空结点):\n");
TreeNode* root = createBinaryTree();
printf("二叉树中结点的个数为:%d\n", countNodes(root));
return 0;
}
```
输入样例:
```
请输入二叉树的结点(-1表示空结点):
1 2 4 -1 -1 5 -1 -1 3 -1 -1
```
输出样例:
```
二叉树中结点的个数为:5
```
用c语言写出程序:统计二叉树中叶子结点的个数
当然,以下是用C语言编写的程序来统计二叉树中叶子节点的个数:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树的结构
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// 创建新节点
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("内存分配失败\n");
exit(1);
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// 统计叶子节点的个数
int countLeaves(struct Node* root) {
if (root == NULL) {
return 0;
}
if (root->left == NULL && root->right == NULL) {
return 1;
}
return countLeaves(root->left) + countLeaves(root->right);
}
int main() {
// 创建二叉树
struct Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
// 统计叶子节点的个数
int numLeaves = countLeaves(root);
printf("叶子节点的个数为:%d\n", numLeaves);
return 0;
}
```
以上程序创建了一个二叉树,并使用递归方法统计二叉树中叶子节点的个数。在这个例子中,二叉树的叶子节点个数为3个。
阅读全文
相关推荐
















