↓快轉到主要內容
  1. LeetCode/

LeetCode 108: Convert Sorted Array to Binary Search Tree

·1 分鐘· ·
LeetCode Easy Array Divide-and-Conquer Tree Binary-Search-Tree
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-08-16

  • 提交紀錄:Runtime Error ×5 → Accepted → Runtime Error ×2 → Accepted → Runtime Error → Accepted ×2

解題思路
#

陣列已排序,所以中間的元素左邊都比它小、右邊都比它大,剛好當根(Tree 模板三)。左右兩半各自遞迴,每次都從中間切,兩邊大小最多差 1,高度平衡。用 index 傳範圍,避免每次切片複製。

我的嘗試
#

前面幾版右半邊切成 nums[mid:],把中間的元素也包含進去,只有一個元素時一直切出同一段,無限遞迴(RecursionError);也有幾版對 None 取屬性。

正確解法
#

class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
        def build(lo, hi):
            if lo > hi:
                return None
            mid = (lo + hi) // 2
            return TreeNode(nums[mid], build(lo, mid - 1), build(mid + 1, hi))
        return build(0, len(nums) - 1)

複雜度
#

時間 O(n),空間 O(log n)。

要特別避免的錯誤
#

  • 遞迴的範圍要排除 mid 自己,不然會無限遞迴。

面試口說整理
#

排序陣列的中間元素當根,左右兩半遞迴建子樹,兩邊大小最多差一,所以高度平衡。用 index 傳範圍,時間 O(n)。

相關文章

LeetCode 110: Balanced Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Binary-Tree
LeetCode 110 解題筆記:每一個節點的左右高度差都不能超過 1;後序回傳高度,不平衡時回傳 -1 一路傳上去
LeetCode 111: Minimum Depth of Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 111 解題筆記:最小深度要到葉子才算;只有一邊有小孩時不能拿空的那邊(深度 0)當最小值
LeetCode 112: Path Sum
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 112 解題筆記:往下走時把 targetSum 減掉目前的值,到葉子時剛好是 0(或等於葉子的值)就成立
LeetCode 119: Pascal's Triangle II
·1 分鐘
LeetCode Easy Array Dynamic-Programming
LeetCode 119 解題筆記:只要第 rowIndex 列,用一維陣列從右往左更新,空間 O(k)
LeetCode 100: Same Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 100 解題筆記:兩邊都是空的才相同;一邊空一邊不空就不同;都不空時比值再遞迴比左右
LeetCode 101: Symmetric Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 101 解題筆記:左子樹跟右子樹互為鏡像:外側跟外側比、內側跟內側比;比的是值,不是節點本身