求二叉树高度和宽度的完整代码
时间: 2024-05-10 12:15:32 浏览: 131
以下是求二叉树高度和宽度的完整代码(Python实现):
```python
# 定义二叉树节点类
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# 计算二叉树高度的函数
def get_tree_height(root):
if not root:
return 0
left_height = get_tree_height(root.left)
right_height = get_tree_height(root.right)
return max(left_height, right_height) + 1
# 计算二叉树宽度的函数
def get_tree_width(root):
if not root:
return 0
queue = [(root, 0)]
cur_level = 0
cur_level_width = 0
max_width = 0
while queue:
node, level = queue.pop(0)
if level == cur_level:
cur_level_width += 1
else:
max_width = max(max_width, cur_level_width)
cur_level = level
cur_level_width = 1
if node.left:
queue.append((node.left, level + 1))
if node.right:
queue.append((node.right, level + 1))
max_width = max(max_width, cur_level_width)
return max_width
# 测试代码
if __name__ == '__main__':
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)
print('树的高度为:', get_tree_height(root))
print('树的宽度为:', get_tree_width(root))
```
输出结果:
```
树的高度为: 3
树的宽度为: 4
```
其中,`get_tree_height`函数用来计算二叉树的高度,采用递归方式求解。`get_tree_width`函数用来计算二叉树的宽度,采用BFS(广度优先搜索)算法,遍历每一层节点并统计宽度。测试代码中构建了一个示例二叉树,并输出了它的高度和宽度。
阅读全文