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.
这个题目很简单,也是用递归来解决。
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 public class Solution { 11 public int minDepth(TreeNode root) { 12 if(root == null) return 0; 13 14 int leftmin = minDepth(root.left); 15 int rightmin = minDepth(root.right); 16 17 if(leftmin==0) return rightmin + 1; 18 if(rightmin==0) return leftmin + 1; 19 return leftmin>rightmin?rightmin+1:leftmin+1; 20 } 21 }