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

LeetCode 938: Range Sum of BST

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

基本資料
#

難易度: easy 第一次嘗試:2022-09-26

  • 提交紀錄:Accepted ×3 → Wrong Answer → Runtime Error → Accepted ×2 → Wrong Answer → Accepted

解題思路
#

BST 的性質可以跳過不可能的子樹(Tree 模板三):

  • 節點 < low:它和整個左子樹都太小,只看右子樹。
  • 節點 > high:只看左子樹。
  • 在範圍內:加上自己,兩邊都要看。

我的嘗試
#

2022 年 9 月有一版定義了遞迴函式卻沒有呼叫它(裡面修改外層的 sum_ 也少了 nonlocal),直接回傳 0。11 月重寫的版本把 low + high 當初始值,等於假設 low、high 一定是樹裡的節點;它通過了測資,但題目沒有這個保證,例如 [9]、low = high = 5 會回傳 10,答案是 0。

正確解法
#

class Solution:
    def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
        if not root:
            return 0
        if root.val < low:
            return self.rangeSumBST(root.right, low, high)
        if root.val > high:
            return self.rangeSumBST(root.left, low, high)
        return root.val + self.rangeSumBST(root.left, low, high) + self.rangeSumBST(root.right, low, high)

複雜度
#

時間 O(n)(最壞),空間 O(h)。

要特別避免的錯誤
#

  • 範圍兩端是包含的。
  • 不要假設 low、high 一定是樹裡的節點。

面試口說整理
#

我利用 BST 的大小關係剪枝:比 low 小只往右找,比 high 大只往左找,在範圍內就加上自己再往兩邊找。時間最壞 O(n)。

相關文章

LeetCode 501: Find Mode in Binary Search Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Binary-Search-Tree Binary-Tree
LeetCode 501 解題筆記:BST 中序是排序的,相同的值會連在一起;中序時數目前這段的長度,比最大值大就重設答案,一樣大就加入
LeetCode 965: Univalued Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 965 解題筆記:每個節點的值都要等於根的值;遞迴時比的是值,不是遞迴回傳的布林值
LeetCode 993: Cousins in Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 993 解題筆記:堂兄弟要同一層、但父節點不同;DFS 記錄 x 和 y 的深度與父節點再比較
LeetCode 897: Increasing Order Search Tree
·1 分鐘
LeetCode Easy Stack Tree Depth-First-Search Binary-Search-Tree
LeetCode 897 解題筆記:中序遍歷,依序把節點接到一條只有右小孩的鏈上,左小孩設成 None;dummy 和移動的尾巴要分開
LeetCode 872: Leaf-Similar Trees
·1 分鐘
LeetCode Easy Tree Depth-First-Search Binary-Tree
LeetCode 872 解題筆記:用 DFS 由左到右收集葉子;BFS 收集的順序是一層一層,不是由左到右
LeetCode 783: Minimum Distance Between BST Nodes
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Search-Tree
LeetCode 783 解題筆記:BST 的中序是由小到大,最小差一定出現在中序相鄰的兩個值之間;記住前一個值逐一比較