高级农民
- 积分
- 1162
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2012-9-16
- 最后登录
- 1970-1-1
|
本帖最后由 laoxie09 于 2015-6-15 07:13 编辑
we only return the depth when we meet leaf nodes(both left and right kids are null).
In the example(given by @mnmunknown)
1
/ \
/ \
2 Null
you may return 1 prematurely (for root node only right kid is empty)
Hope this code helps
public class Solution {
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;
if (root.right == null && root.left == null) return 1;
if (root.right != null && root.left != null) return Math.min(minDepth(root.left),minDepth(root.right)) + 1;
return -1;//just for compile and error check;
}
}
|
|