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.
思路:也是穷举法的方法,每次都取最小的深度。当root==null时 return 0;
当root.left!=null || root.right!=null时,return 1+min(minDep(root.left),minDep(root.right));
当root.left或者root.right有一个为空时,返回1+minDep(root.left)+minDep(root.right);
代码如下(已通过leetcode)
public class Solution {
public int minDepth(TreeNode root) {
if(root==null) return 0;
else {
if(root.left!=null && root.right!=null ) return 1+Math.min(minDepth(root.left), minDepth(root.right));
else return 1+minDepth(root.left)+minDepth(root.right);
}
}
}