用c语言编写求叶子结点的算法
时间: 2024-02-16 21:03:11 浏览: 65
用C语言求二叉树叶子结点
4星 · 用户满意度95%
以下是用C语言编写求二叉树叶子结点数量的算法:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结点结构体
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 创建二叉树
TreeNode* createTree() {
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 = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 7;
root->right->right->left = NULL;
root->right->right->right = NULL;
return root;
}
// 递归求叶子结点数量
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 = createTree();
int leafCount = countLeaf(root);
printf("叶子结点数量:%d\n", leafCount);
return 0;
}
```
在这个算法中,我们使用了递归的方法来遍历二叉树,当遍历到叶子结点时,返回1,否则返回左子树和右子树的叶子结点数量之和。最终,我们可以得到整个二叉树的叶子结点数量。
阅读全文