二叉树高度与广度怎么算
时间: 2024-11-21 21:07:27 浏览: 45
在计算机科学中,二叉树的高度(Height)是指从根节点到最远叶子节点的最长路径上的边数,而广度(即宽度)则是指在同一层的所有节点的数量。
**计算二叉树的高度:**
- 对于空树,高度为0。
- 如果二叉树非空,递归地计算左子树和右子树的高度。取两者的较大值加1,即为当前树的高度。公式可以表示为 `height = max(height(left_subtree), height(right_subtree)) + 1`。
**计算二叉树的广度:**
- 使用队列数据结构,将根节点放入队列,然后开始循环。
- 每次从队列中取出一个节点,并将其左右子节点(如果存在)加入队列,同时计数器加一。
- 当队列为空时,说明已经遍历完所有层级,此时的计数器值就是树的广度。
**示例算法伪代码:**
```python
function tree_height(root):
if root is None:
return 0
else:
left_height = tree_height(root.left)
right_height = tree_height(root.right)
return max(left_height, right_height) + 1
function tree_breadth(root):
if root is None:
return 0
queue = [root]
breadth = 0
while queue:
current_level_size = len(queue)
breadth += 1
for _ in range(current_level_size):
node = queue.pop(0)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
return breadth
```
阅读全文
相关推荐


















