Leetcode-104-111-Max-Min-Depth-BT

🧠 思路总结

  • 104: Max depth
    • 递归 dfs:
      • 空节点返回 0
      • 递归调用左子树和右子树
      • 返回 max(left, right) + 1
  • 111: Min depth
    • root == null → 0
    • 只有一边为空 → 非空那边 + 1
    • 两边都不空 → min(left, right) + 1

❗ 易错点 / 小坑

  • 111: Min depth
    • 不能直接用 min(left, right) + 1
    • 如果一边是 null,必须走另一边
    • 因为最小深度必须到“叶子”,不能走到空就停

✅ 代码(Java)

1
2
3
4
5
6
7
8
9
10
11
/**
* 104. Maximum Depth of Binary Tree
*/
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 111. Minimum Depth of Binary Tree
*/
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
// 如果左子树为空,必须走右子树
if (root.left == null) {
return minDepth(root.right) + 1;
}
// 如果右子树为空,必须走左子树
if (root.right == null) {
return minDepth(root.left) + 1;
}
// 两边都不为空,返回较小的 + 1
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}

Leetcode-104-111-Max-Min-Depth-BT
https://powersixxx.github.io/leetcode-blog/2026/01/13/Leetcode-104-111-Max-Min-Depth-BT/
作者
Baowen Liu
发布于
2026年1月13日
许可协议