编写代码,在以二叉链表存储的二叉树中,求度为2的节点的个数
时间: 2024-02-13 13:02:31 浏览: 22
以下是求度为2的节点个数的代码实现:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def count_degree_2(root):
if root is None:
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 = 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)
root.right.right.left = TreeNode(8)
print(count_degree_2(root)) # 输出 3
```
解释:遍历二叉树,对于每个节点,如果它的左右子节点都存在,则说明它是度为2的节点,累加计数器,最后返回计数器的值即可。