二叉树中度为2的结点个数 python
时间: 2024-05-16 19:16:21 浏览: 17
可以通过递归遍历二叉树来统计度为2的节点个数。具体实现可以参考如下Python代码:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def count_degree_2(root: TreeNode) -> int:
if not root:
return 0
count = 0
if root.left and root.right: # 如果当前节点的左右子节点都存在
count = 1
count += count_degree_2(root.left)
count += count_degree_2(root.right)
return count
```
其中,`TreeNode`是二叉树的节点类,`count_degree_2`函数表示统计二叉树中度为2的节点个数。在函数中,首先判断当前节点的左右子节点是否都存在,如果存在则将计数器`count`加1,然后递归遍历左子树和右子树,将它们的度为2的节点个数加到计数器中,最后返回计数器的值即可。
相关问题
统计二叉树中度为2的结点个数
统计二叉树中度为2的结点个数可以通过递归的方式实现。具体步骤如下:
1. 判断当前结点是否存在,若不存在则返回0;
2. 判断当前结点的度数是否为2,若是则计数器加1;
3. 递归遍历当前结点的左子树,统计度为2的结点个数;
4. 递归遍历当前结点的右子树,统计度为2的结点个数;
5. 返回计数器的值。
以下是代码示例:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def count_degree_2(root):
if not root:
return 0
count = 0
if root.left and root.right:
count += 1
count += count_degree_2(root.left)
count += count_degree_2(root.right)
return count
```
其中,`root`为根节点。
python求二叉树中度为2的结点个数代码
下面是一个递归实现的示例代码:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def count_nodes(root):
if not root:
return 0
count = 0
if root.left and root.right:
count = 1
count += count_nodes(root.left) + count_nodes(root.right)
return count
```
其中 `TreeNode` 是二叉树的节点类,`val` 是节点的值,`left` 和 `right` 分别是左子树和右子树。 `count_nodes` 函数递归地遍历二叉树,如果当前节点的左右子树均不为空,则该节点为度为2的节点,计数器加一,并继续递归遍历其左右子树。最后返回计数器的值即可。
使用示例:
```python
# 构建一棵二叉树
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
# 计算度为2的节点个数
count = count_nodes(root)
print(count) # 输出 3
```
在上面的示例中,输入的二叉树共有3个度为2的节点,即节点2、3和6。