c语言求二叉树的叶子个数代码
时间: 2023-06-06 14:07:21 浏览: 110
c代码-求二叉树的叶子节点和高度
5星 · 资源好评率100%
下面是 C 语言求二叉树叶子节点个数的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结构体
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 创建二叉树节点
TreeNode* createNode(int val) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
// 计算二叉树叶子节点个数
int countLeafNodes(TreeNode* root) {
if (root == NULL) {
return 0;
}
if (root->left == NULL && root->right == NULL) {
return 1;
}
return countLeafNodes(root->left) + countLeafNodes(root->right);
}
int main() {
// 创建二叉树
TreeNode* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
// 计算叶子节点个数并输出
int leafNodes = countLeafNodes(root);
printf("The number of leaf nodes in the binary tree is: %d", leafNodes);
return 0;
}
```
注意:本代码没有针对空指针进行处理,实际使用中需要注意空指针的情况。
阅读全文