因为当我们递归的时候:当一个结点只有左子树或者右子树,我们不能直接返回 0,因为压根儿这边就没有树,谈不上是不是最小。我们要返回另一半的 depth (也就是 left + 1 或者 right + 1)。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */publicclassSolution {publicintminDepth(TreeNode root) {if (root ==null) {return0; }int left =minDepth(root.left);int right =minDepth(root.right);if (left ==0|| right ==0) {return left > right ? left +1: right +1; }returnMath.min(left, right) +1; }}
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */publicclassSolution {publicintminDepth(TreeNode root) {if (root ==null) {return0; } returngetMin(root); }privateintgetMin(TreeNode root) {if (root ==null) {returnInteger.MAX_VALUE; }if (root.left==null&&root.right==null) {return1; }returnMath.min(getMin(root.left),getMin(root.right)) +1; }}