Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
else if(root.left==null&&root.right==null){
return 1;
}
return minD(root,1);
}
int minD(TreeNode root,int depth){
if(root.left==null&&root.right==null){
return depth;
}
int left=0x7fffffff;
int right=0x7fffffff;
if(root.left!=null){
left=minD(root.left,depth+1);
}
if(root.right!=null){
right=minD(root.right,depth+1);
}
return min(left,right);
}
int min(int a,int b){
return a>b?b:a;
}
}
190

被折叠的 条评论
为什么被折叠?



