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 nearest leaf node.
分析:
二叉树用递归。
/**
* Definition for binary tree
* 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;
int lMin = minDepth(root.left);
int rMin = minDepth(root.right);
if(lMin==0 && rMin==0) return 1;
//下面这两行是避免把只有一个孩子的中间节点当成叶子节点
if(lMin == 0) lMin = Integer.MAX_VALUE;
if(rMin == 0) rMin = Integer.MAX_VALUE;
return Math.min(lMin, rMin) + 1;
}
}