c语言计算二叉树左孩子总数
时间: 2023-10-04 21:05:01 浏览: 36
计算二叉树左孩子总数的方法是使用递归。首先,定义一个函数来计算二叉树中左孩子的数量。在该函数中,我们可以通过递归地遍历二叉树来计算左孩子的数量。
具体的算法如下:
1. 定义一个计数器变量count,用于记录左孩子的数量。
2. 如果二叉树为空,则返回0。
3. 如果当前节点存在左子节点,则递归地遍历左子树,并将返回的结果加到count中。
4. 返回count的值。
下面是C语言实现该算法的代码:
```c
#include <stdio.h>
#include <stdlib.h>
//定义二叉树的结构体
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
//计算二叉树左孩子总数的函数
int countLeftChild(TreeNode* root) {
if (root == NULL) {
return 0;
}
int count = 0;
if (root->left != NULL) {
count++;
count += countLeftChild(root->left);
}
count += countLeftChild(root->right);
return count;
}
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;
//计算左孩子的数量
int count = countLeftChild(root);
printf("The number of left children in the binary tree is %d", count);
return 0;
}
```
输出结果为:The number of left children in the binary tree is 3。