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.
思路:这题和求最深深度类似,同样是递归,唯一需要注意一点的是:
4 / 这种情况,返回的深度应该是 2 ,而不是1; 2
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public int minDepth(TreeNode root) { 12 int lDepth = 0,rDepth = 0; 13 if (root==null) 14 return 0; //如果一开始传进来空树,则深度为0; 15 if (root.left!=null&&root.right==null){ 16 lDepth = minDepth(root.left); //如果出现了左儿子非空,右儿子空,则 17 return lDepth+1; //只递归左儿子就好了 18 } 19 else if (root.left==null&&root.right!=null){ 20 rDepth = minDepth(root.right); //与上同理 21 return rDepth+1; 22 } 23 else{ 24 lDepth = minDepth(root.left); //否则的话,同时递归左右孩子 25 rDepth = minDepth(root.right); 26 } 27 if (lDepth>rDepth) 28 lDepth = rDepth; //选择左右孩子中深度小的返回; 29 return lDepth+1; 30 } 31 }