统计二叉树中度为2的结点个数
时间: 2024-03-23 14:43:19 浏览: 26
统计二叉树中度为2的节点个数,可以通过递归方式实现。对于每个节点,判断其左右子树的度数,如果度数都为2,则当前节点的度数也为2。
以下是该问题的递归实现代码:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def count_degree_2_nodes(root):
if root is None:
return 0
count = 0
if root.left and root.right:
count += 1
count += count_degree_2_nodes(root.left)
count += count_degree_2_nodes(root.right)
return count
```
其中,`count_degree_2_nodes` 函数接收一个二叉树的根节点作为参数,返回该二叉树中度为2的节点个数。如果根节点为空,则返回0。否则,对于非空节点,判断其左右子树的度数,如果都为2,则将计数器加1,并递归遍历其左右子树。最后返回计数器的值即可。
相关问题
统计二叉树中度为1结点个数c++
可以使用递归的方式来统计二叉树中度为1的节点数量。首先,我们需要定义二叉树的数据结构:
```cpp
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
```
然后,我们可以使用一个递归函数来统计二叉树中度为1的节点数量:
```cpp
int countDegreeOneNodes(TreeNode* root) {
if (root == NULL) {
return 0;
}
int count = 0;
// 如果当前节点的度为1,则count加1
if ((root->left == NULL && root->right != NULL) || (root->left != NULL && root->right == NULL)) {
count++;
}
// 递归统计左子树和右子树中度为1的节点数量
count += countDegreeOneNodes(root->left);
count += countDegreeOneNodes(root->right);
return count;
}
```
通过调用 `countDegreeOneNodes` 函数并传入二叉树的根节点,即可得到度为1的节点数量。
统计二叉树中度为1度结点个数
在一棵二叉树中,度为1的节点有两种情况:左子树为空或右子树为空。因此,我们可以通过遍历二叉树,统计左子树为空或右子树为空的节点个数来得到度为1的节点个数。
具体实现方法可以使用递归。对于一个节点,如果其左子树为空或右子树为空,则该节点的度为1;否则,将其左子树和右子树分别递归处理,最终将所有子树的度为1的节点个数加起来即为整棵树的度为1的节点个数。
以下是一个示例的 Python 代码实现:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def count_degree_one_nodes(root):
if not root:
return 0
count = 0
if (not root.left and root.right) or (root.left and not root.right):
count = 1
count += count_degree_one_nodes(root.left) + count_degree_one_nodes(root.right)
return count
```
其中,`TreeNode` 表示二叉树的节点,`count_degree_one_nodes` 函数接收树的根节点作为参数,并返回度为1的节点个数。在函数中,如果当前节点的左子树为空或右子树为空,则将 `count` 计数器加1,然后递归处理其左子树和右子树,并将结果相加。最终,函数返回计数器的值,即为度为1的节点个数。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)