二叉樹的最小深度踩坑

今天做題的時候做到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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章