设二叉树中每个结点的元素均为一个字符,按先序遍历的顺序建立二叉链表,编写三个递归算法对二叉树的结点(度为0、1、2)个数进行统计。
时间: 2024-05-14 15:19:24 浏览: 140
递归算法如下:
```python
class Node:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
def count_leaf(node):
if not node:
return 0
if not node.left and not node.right:
return 1
return count_leaf(node.left) + count_leaf(node.right)
def count_degree_one(node):
if not node:
return 0
if (node.left and not node.right) or (node.right and not node.left):
return 1
return count_degree_one(node.left) + count_degree_one(node.right)
def count_degree_two(node):
if not node:
return 0
if node.left and node.right:
return 1
return count_degree_two(node.left) + count_degree_two(node.right)
```
其中 `count_leaf` 统计叶子结点个数, `count_degree_one` 统计度为1的结点个数, `count_degree_two` 统计度为2的结点个数。
阅读全文