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

LeetCode 530: Minimum Absolute Difference in BST

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

基本資料
#

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

  • 提交紀錄:Accepted ×2

解題思路
#

BST 的中序遍歷是排序好的序列,排序後最接近的兩個數一定相鄰(Tree 模板三)。中序走的時候記住前一個值,跟目前的值相減更新答案。這題和 LC 783 是同一題。

我的解法
#

class Solution:
    def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
        best, prev = float("inf"), None
        stack, cur = [], root
        while cur or stack:
            while cur:
                stack.append(cur)
                cur = cur.left
            cur = stack.pop()
            if prev is not None:
                best = min(best, cur.val - prev)
            prev = cur.val
            cur = cur.right
        return best

複雜度
#

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

要特別避免的錯誤
#

  • 最接近的兩個值不一定是父子,要比中序相鄰的值。

面試口說整理
#

BST 中序是排序的,最小差一定在相鄰的兩個值之間,所以我中序遍歷時記住前一個值,每次相減更新最小值。時間 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 404: Sum of Left Leaves
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 404 解題筆記:DFS 時告訴小孩自己是不是左小孩,只有「是左小孩而且是葉子」才加
LeetCode 226: Invert Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 226 解題筆記:每個節點交換左右小孩;用同時指定,避免先改掉的那邊被拿來用
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 100: Same Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 100 解題筆記:兩邊都是空的才相同;一邊空一邊不空就不同;都不空時比值再遞迴比左右