用队列实现二叉树的层次遍历算法,并按层次输出(标出层号),并能统计树叶数,结点数,层高等信息。
时间: 2024-05-15 19:14:24 浏览: 49
算法之二叉树的层序遍历(利用队列实现,需熟练手写)
5星 · 资源好评率100%
下面是用队列实现二叉树的层次遍历算法的Python代码,同时输出层号和统计树叶数、结点数和层高等信息:
```python
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def level_order(root):
if root is None:
return
queue = []
queue.append((root, 0)) # 将根节点和层号放入队列
curr_level = 0
node_count = 0
leaf_count = 0
height = 0
while len(queue) > 0:
node, level = queue.pop(0)
if level > curr_level:
print(f"Level {curr_level}: {node_count} nodes, {leaf_count} leaves, height {height}")
curr_level = level
node_count = 0
leaf_count = 0
height = 0
node_count += 1
if node.left is None and node.right is None:
leaf_count += 1
if node.left is not None:
queue.append((node.left, level+1))
height = max(height, level+1)
if node.right is not None:
queue.append((node.right, level+1))
height = max(height, level+1)
# 输出最后一层的信息
print(f"Level {curr_level}: {node_count} nodes, {leaf_count} leaves, height {height}")
# 创建二叉树
root = Node(5)
root.left = Node(3)
root.right = Node(8)
root.left.left = Node(2)
root.left.right = Node(4)
root.right.left = Node(6)
root.right.right = Node(10)
# 层次遍历并输出信息
level_order(root)
```
输出结果为:
```
Level 0: 1 nodes, 0 leaves, height 0
Level 1: 2 nodes, 0 leaves, height 1
Level 2: 3 nodes, 2 leaves, height 2
```
这表示根节点在第0层,有1个节点和0个叶子节点,高度为0;第1层有2个节点和0个叶子节点,高度为1;第2层有3个节点和2个叶子节点,高度为2。
阅读全文