编写c语言代码,在以二叉链表存储的二叉树中,求度为2的节点的个数
时间: 2024-02-13 14:02:31 浏览: 115
以下是求度为2的节点个数的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
int count_degree_2(TreeNode* root) {
if (root == NULL) {
return 0;
}
int count = 0;
if (root->left && root->right) {
count++;
}
count += count_degree_2(root->left);
count += count_degree_2(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;
root->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->left->val = 6;
root->right->right = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->val = 7;
root->right->right->left = (TreeNode*)malloc(sizeof(TreeNode));
root->right->right->left->val = 8;
printf("%d", count_degree_2(root)); // 输出 3
return 0;
}
```
解释:遍历二叉树,对于每个节点,如果它的左右子节点都存在,则说明它是度为2的节点,累加计数器,最后返回计数器的值即可。注意要动态分配内存来创建二叉树节点。
阅读全文