题目

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明:叶子节点是指没有子节点的节点。

示例 1: image.png

输入:root = [3,9,20,null,null,15,7]
输出:2

示例 2:

输入:root = [2,null,3,null,4,null,5,null,6]
输出:5

提示:

树中节点数的范围在 [0, 10^5] 内
-1000 <= Node.val <= 1000

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/minimum-depth-of-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

和二叉树的最大深度问题相反,对于一般情况,将左右子树中较大的深度换成较小的就好了。

但是需要注意,如果有一边子树为空,那么只能返回另一边的深度,因为路径是从根节点到最近的叶子结点。例如下面这棵树,最小深度为2,不是1。

  1. 1
  2. \
  3. 2

代码

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public int minDepth(TreeNode root) {
  12. if (root == null) {
  13. return 0;
  14. }
  15. int ldepth = minDepth(root.left);
  16. int rdepth = minDepth(root.right);
  17. if (ldepth == 0) {
  18. return rdepth + 1;
  19. } else if (rdepth == 0) {
  20. return ldepth + 1;
  21. }
  22. return ldepth < rdepth ? ldepth + 1 : rdepth + 1;
  23. }
  24. }

还有一种更加优雅的写法:

  1. class Solution {
  2. public int minDepth(TreeNode root) {
  3. if (root == null) return 0;
  4. int l_high = minDepth(root.left);
  5. int r_high = minDepth(root.right);
  6. if (l_high == 0 || r_high == 0) {
  7. return l_high + r_high + 1;
  8. }
  9. return l_high < r_high ? l_high + 1 : r_high + 1;
  10. }
  11. }