请为二叉树类binaryTree增加一个功能,统计度数为2的节点个数,用C++语言
时间: 2023-05-31 07:01:57 浏览: 67
以下是实现代码:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
typedef struct BinaryTree {
TreeNode *root;
} BinaryTree;
int countDegreeTwoNodes(TreeNode *node) {
if (node == NULL) {
return 0;
}
int count = 0;
if (node->left != NULL && node->right != NULL) {
count++;
}
count += countDegreeTwoNodes(node->left);
count += countDegreeTwoNodes(node->right);
return count;
}
int countDegreeTwoNodesInBinaryTree(BinaryTree *tree) {
return countDegreeTwoNodes(tree->root);
}
int main() {
TreeNode *node1 = (TreeNode *)malloc(sizeof(TreeNode));
TreeNode *node2 = (TreeNode *)malloc(sizeof(TreeNode));
TreeNode *node3 = (TreeNode *)malloc(sizeof(TreeNode));
TreeNode *node4 = (TreeNode *)malloc(sizeof(TreeNode));
TreeNode *node5 = (TreeNode *)malloc(sizeof(TreeNode));
node1->data = 1;
node2->data = 2;
node3->data = 3;
node4->data = 4;
node5->data = 5;
node1->left = node2;
node1->right = node3;
node2->left = node4;
node2->right = NULL;
node3->left = node5;
node3->right = NULL;
node4->left = NULL;
node4->right = NULL;
node5->left = NULL;
node5->right = NULL;
BinaryTree *tree = (BinaryTree *)malloc(sizeof(BinaryTree));
tree->root = node1;
printf("The number of degree-2 nodes in the binary tree is: %d\n", countDegreeTwoNodesInBinaryTree(tree));
free(node1);
free(node2);
free(node3);
free(node4);
free(node5);
free(tree);
return 0;
}
```
在上面的代码中,我们先定义了一个 `countDegreeTwoNodes` 函数,该函数用于统计一个节点为根的子树中度数为2的节点个数。在该函数中,我们首先判断当前节点的左右子节点是否都存在,如果都存在则将计数器加1,然后递归调用该函数统计左右子树中的度数为2的节点个数,最后返回总数。
然后,我们定义了一个 `countDegreeTwoNodesInBinaryTree` 函数,该函数用于统计整个二叉树中度数为2的节点个数。在该函数中,我们调用 `countDegreeTwoNodes` 函数并传入二叉树的根节点,最终返回统计结果。
最后,在 `main` 函数中,我们创建了一个二叉树并统计其中度数为2的节点个数,然后释放了所有动态分配的内存。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)