📋 题目描述
给定一个二叉树的根节点 root,返回其最大深度。
二叉树的最大深度 是指从根节点到最远叶子节点的最长路径上的节点数量。
示例:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回深度 3
🧠 核心思路
基本定义
-
空树的深度为 0
-
叶子节点的深度为 1
-
非叶子节点的深度 = max(左子树深度, 右子树深度) + 1
关键:
树的深度问题本质上是递归问题,因为:
-
树本身就是递归定义的数据结构
-
整棵树的深度可以通过子树的深度推导出来
-
问题可以分解为相同结构的子问题
🔍 解法
解法一:递归(分治策略)⭐️ 面试首选
python
def maxDepth(root: Optional[TreeNode]) -> int:
if not root:
return 0
left_depth = maxDepth(root.left)
right_depth = maxDepth(root.right)
return max(left_depth, right_depth) + 1
一行简洁版:
python
def maxDepth(root):
return 0 if not root else max(maxDepth(root.left), maxDepth(root.right)) + 1
复杂度分析:
-
时间复杂度:O(n) - 每个节点访问一次
-
空间复杂度:O(h) - 递归栈深度,h为树高
解法二:BFS层序遍历(迭代)
python
from collections import deque
def maxDepth(root):
if not root:
return 0
queue = deque([root])
depth = 0
while queue:
# 处理当前层的所有节点
level_size = len(queue)
for _ in range(level_size):
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
depth += 1 # 完成一层处理
return depth
可视化过程:
text
队列变化:[3] → 深度=1
[9,20] → 深度=2
[15,7] → 深度=3
[] → 结束
复杂度分析:
-
时间复杂度:O(n)
-
空间复杂度:O(w) - w为树的最大宽度
解法三:DFS迭代(栈模拟)
python
def maxDepth(root):
if not root:
return 0
stack = [(root, 1)] # (节点, 当前深度)
max_depth = 0
while stack:
node, depth = stack.pop()
max_depth = max(max_depth, depth)
# 先右后左,保证左子树先被处理
if node.right:
stack.append((node.right, depth + 1))
if node.left:
stack.append((node.left, depth + 1))
return max_depth
📊 方法对比
| 方法 | 代码简洁度 | 空间占用 | 适用场景 | 面试推荐 |
|---|---|---|---|---|
| 递归DFS | ⭐⭐⭐⭐⭐ | O(h) | 常规二叉树 | 首选 |
| BFS迭代 | ⭐⭐⭐⭐ | O(w) | 宽扁树 | 第二选择 |
| DFS迭代 | ⭐⭐⭐ | O(h) | 深度大时 | 备用方案 |
空间复杂度说明:
-
h: 树的高度(平衡树h=log n,链表h=n)
-
w: 树的最大宽度(最后一层节点数)
💡 面试技巧
回答策略
-
先写递归解法(80%情况足够)
-
主动分析复杂度
-
准备迭代版本(以防被问)
-
讨论边界情况(空树、单节点、链表状树)
常见问题
Q: 如果树特别深(10^5层),递归会栈溢出吗?
A: 会。Python默认递归深度约1000层,深度很大时应该使用迭代方法。
Q: 能用BFS求最小深度吗?
A: 可以!BFS找到的第一个叶子节点就是最小深度。
Q: 时间和空间复杂度哪个更重要?
A: 时间O(n)通常必须,空间可以根据实际情况选择。宽树用DFS,深树用BFS。
🚀 进阶思考
变体1:求最小深度**√**
python
def minDepth(root):
if not root:
return 0
if not root.left:
return minDepth(root.right) + 1
if not root.right:
return minDepth(root.left) + 1
return min(minDepth(root.left), minDepth(root.right)) + 1
变体2:判断平衡二叉树
python
def isBalanced(root):
def check(node):
if not node:
return 0, True
left_h, left_b = check(node.left)
right_h, right_b = check(node.right)
balanced = left_b and right_b and abs(left_h - right_h) <= 1
return max(left_h, right_h) + 1, balanced
return check(root)[1]
🎯 总结要点
-
递归是树的天然解法 - 利用树的自相似性
-
分治策略 - 将问题分解为左右子树
-
递归三要素:
-
终止条件:节点为空
-
递推关系:max(左,右)+1
-
返回值:当前子树深度
-
-
面试心法:
-
5分钟内写出递归解法
-
2分钟内解释清楚
-
1分钟内分析复杂度
-
📚 相关题目
最后记住:二叉树问题,先想递归;递归不行,迭代来凑;分治思想,贯穿始终。