File tree Expand file tree Collapse file tree 1 file changed +7
-3
lines changed Expand file tree Collapse file tree 1 file changed +7
-3
lines changed Original file line number Diff line number Diff line change @@ -46,17 +46,21 @@ public int minDepthRec(TreeNode root) {
46
46
* 这种递归解法更简单。因为在本层递归中不需要考虑左右子树是否为NULL的情况。因为我们直接
47
47
把 null 设置为返回一个最大值,这样的话,如果出现空子树,它不会影响最小值。但是如果左
48
48
右均为空,则应返回1(即是仅仅为根节点)
49
+
50
+ 而且这种做法更加合理。 因为如果是空树,应该是无法到达才是。这时就应该将值设置为最大。
49
51
* */
50
52
public int minDepthHelp (TreeNode root ) {
51
53
if (root == null ) {
52
54
return Integer .MAX_VALUE ;
53
55
}
54
56
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 ) {
57
59
return 1 ;
58
60
}
59
- return min + 1 ;
61
+
62
+ // root不是叶子节点,输出左右子树的最小值,再加上root本身
63
+ return 1 + Math .min (minDepthHelp (root .left ), minDepthHelp (root .right ));
60
64
}
61
65
62
66
/*
You can’t perform that action at this time.
0 commit comments