算法思想:
1. 对于每个节点,先判断是否为空,若为空,则返回0。
2. 对于非空节点,我们首先判断该节点是否同时具有左右子节点,如果是,将计数器加1。
3. 然后递归地调用函数计算左子节点和右子节点具有两个子节点的节点数量,并将两者相加。
4. 最后返回计数器的值即可。
#include <stdio.h>
#include <stdlib.h>
// 二叉树结点定义
typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;
// 创建二叉树结点
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("内存分配失败\n");
exit(1);
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// 计算具有两个子节点的节点数量
int countNodesWithTwoChildren(Node* root) {
if (root == NULL) {
return 0;
}
int count = 0;
if (root->left != NULL && root->right != NULL) {
count++;
}
count += countNodesWithTwoChildren(root->left);
count += countNodesWithTwoChildren(root->right);
return count;
}
int main() {
// 创建二叉树
Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->left = createNode(6);
root->right->right = createNode(7);
// 计算具有两个子节点的节点数量
int result = countNodesWithTwoChildren(root);
printf("具有两个子节点的节点数量为:%d\n", result);
return 0;
}