Skip to content

Commit dc15508

Browse files
committed
min
1 parent 2d0cf85 commit dc15508

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

tree/MinDepth.java

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,17 +46,21 @@ public int minDepthRec(TreeNode root) {
4646
* 这种递归解法更简单。因为在本层递归中不需要考虑左右子树是否为NULL的情况。因为我们直接
4747
把 null 设置为返回一个最大值,这样的话,如果出现空子树,它不会影响最小值。但是如果左
4848
右均为空,则应返回1(即是仅仅为根节点)
49+
50+
而且这种做法更加合理。 因为如果是空树,应该是无法到达才是。这时就应该将值设置为最大。
4951
* */
5052
public int minDepthHelp(TreeNode root) {
5153
if (root == null) {
5254
return Integer.MAX_VALUE;
5355
}
5456

55-
int min = Math.min(minDepthHelp(root.left), minDepthHelp(root.right));
56-
if (min == Integer.MAX_VALUE) {
57+
// 如果root是叶子节点,直接就可以退出咯。
58+
if (root.left == null && root.right == null) {
5759
return 1;
5860
}
59-
return min + 1;
61+
62+
// root不是叶子节点,输出左右子树的最小值,再加上root本身
63+
return 1 + Math.min(minDepthHelp(root.left), minDepthHelp(root.right));
6064
}
6165

6266
/*

0 commit comments

Comments
 (0)