今天做題的時候做到leetcode 111,二叉樹最小深度。
看了一眼以爲可以秒殺(我太天真了)
寫下如下代碼
return root == null ? 0 : Math.min(minDepth(root.left),minDepth(root.right))+1;
然後。。。gg了
原因是
當存在這樣左子樹或者柚子樹爲空的情況下,使用如上代碼輸出爲1,但1是有子節點的,所以不符合最小深度(葉子結點到根節點)的要求,測試報錯。
應該排除一下這種情況
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
if(root.left == null && root.right != null){
return 1 + minDepth(root.right);
}
if(root.left != null && root.right == null){
return 1 + minDepth(root.left);
}
return root == null ? 0 : Math.min(minDepth(root.left),minDepth(root.right))+1;
}
AC