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.
题意:给出一个二叉树,求从根到叶子结点最短的路径
思路:用DFS方法
/**
* 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;
if (root.left == null && root.right == null) return 1;
int l = Integer.MAX_VALUE, r = Integer.MAX_VALUE;
if (root.left != null) l = 1 + minDepth(root.left);
if (root.right != null) r = 1 + minDepth(root.right);
return Math.min(l, r);
}
}