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.
Solution:O(n)
public class Solution {
public int minDepth(TreeNode root) {
if(root == null)
return 0;
int min = 1;
if(root.left == null && root.right ==null ){
}else if(root.left == null){
min+= minDepth(root.right);
}else if(root.right == null){
min+= minDepth(root.left);
}else{
min+= Math.min(minDepth(root.left),minDepth(root.right));
}
return min;
}
}
沒有留言:
張貼留言