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.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3
/
9 20
/
15 7
return its minimum depth = 2.
结果2 = 左边加1得出来的。
如果是最小值并且一边为空的话,就是0 + 1了,这是不准确的,因为没路的一边其实没用。其实是非空的一侧才长度增加
概括是:有路就找最短,没路就找有路的。这是和最大长度的一个区别。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public int minDepth(TreeNode root) { //cc if (root == null) return 0; int left = minDepth(root.left); int right = minDepth(root.right); int min = Math.min(left, right); if (left == 0) { return right + 1; }else if (right == 0) { return left + 1; }else return min + 1; } }