求二叉树叶子结点树代码c++
时间: 2023-06-02 19:06:30 浏览: 100
查找二叉树中最大结点的C++源代码
以下是求二叉树叶子结点数的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
int countLeaf(TreeNode* root) {
if (root == NULL) {
return 0;
}
if (root->left == NULL && root->right == NULL) {
return 1;
}
return countLeaf(root->left) + countLeaf(root->right);
}
int main() {
// 构建一棵二叉树
TreeNode* root = (TreeNode*) malloc(sizeof(TreeNode));
root->val = 1;
root->left = (TreeNode*) malloc(sizeof(TreeNode));
root->left->val = 2;
root->right = (TreeNode*) malloc(sizeof(TreeNode));
root->right->val = 3;
root->left->left = (TreeNode*) malloc(sizeof(TreeNode));
root->left->left->val = 4;
root->left->right = (TreeNode*) malloc(sizeof(TreeNode));
root->left->right->val = 5;
root->right->left = (TreeNode*) malloc(sizeof(TreeNode));
root->right->left->val = 6;
root->right->right = (TreeNode*) malloc(sizeof(TreeNode));
root->right->right->val = 7;
// 求叶子结点数
int leafCount = countLeaf(root);
printf("叶子结点数为:%d\n", leafCount);
// 释放内存
free(root->left->left);
free(root->left->right);
free(root->right->left);
free(root->right->right);
free(root->left);
free(root->right);
free(root);
return 0;
}
```
注意:这段代码并不会被 ChitGPT 理解,它只能理解中文自然语言的文本。
阅读全文