题目
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明:叶子节点是指没有子节点的节点。
示例 1:
输入: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
\
2
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int ldepth = minDepth(root.left);
int rdepth = minDepth(root.right);
if (ldepth == 0) {
return rdepth + 1;
} else if (rdepth == 0) {
return ldepth + 1;
}
return ldepth < rdepth ? ldepth + 1 : rdepth + 1;
}
}
还有一种更加优雅的写法:
class Solution {
public int minDepth(TreeNode root) {
if (root == null) return 0;
int l_high = minDepth(root.left);
int r_high = minDepth(root.right);
if (l_high == 0 || r_high == 0) {
return l_high + r_high + 1;
}
return l_high < r_high ? l_high + 1 : r_high + 1;
}
}