尝试一
result:答案正确:恭喜!您提交的程序通过了所有的测试用例
code:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
//mean the min depth
private int minDepth;
public int run(TreeNode root) {
minDepth=Integer.MAX_VALUE;
if(root==null){
minDepth=0;
return minDepth;
}
run(root,0);
return minDepth;
}
/*now:the current depth */
private void run(TreeNode root,int now){
/*another end mark of recursive function*/
if(root==null){
return ;
}
now++;
run(root.left,now);
run(root.right,now);
/*warning:the end mark of recursive function is root.left==null && root.right==null */
if(root.left==null && root.right==null){
if(now<minDepth){
minDepth=now;
}
return;
}
}
}
分析:注意递归结束标识有root.left==null && root.right==null
,此时才应该将最小depth存到minDepth。
结论
- 求整数的最大值:Integer.MAX_VALUE;