在一个非空二叉树中统计叶子节点个数。 效果截图: C语言程序代码:
时间: 2024-03-09 08:46:49 浏览: 49
统计二叉树的结点个数的参考程序
5星 · 资源好评率100%
好的,下面是 C 语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义二叉树节点结构体
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 统计叶子节点个数的函数
int count_leaf_node(TreeNode* root) {
if (!root) {
return 0;
}
if (!root->left && !root->right) {
return 1;
}
return count_leaf_node(root->left) + count_leaf_node(root->right);
}
// 测试
int main() {
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->val = 2;
root->left->left = (TreeNode*)malloc(sizeof(TreeNode));
root->left->left->val = 4;
root->left->left->left = NULL;
root->left->left->right = NULL;
root->left->right = (TreeNode*)malloc(sizeof(TreeNode));
root->left->right->val = 5;
root->left->right->left = NULL;
root->left->right->right = NULL;
root->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->val = 3;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 6;
root->right->left->left = NULL;
root->right->left->right = NULL;
root->right->right = NULL;
printf("%d\n", count_leaf_node(root)); // 输出 3
return 0;
}
```
希望能够解决你的问题!
阅读全文