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

LeetCode 235: Lowest Common Ancestor of a Binary Search Tree

·1 分鐘· ·
LeetCode Medium 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.
目錄

基本資料
#

難易度: medium 第一次嘗試:2022-08-22

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

解題思路
#

利用 BST 的大小關係,不用搜尋整棵樹(Tree 模板四):

  • p、q 都比目前節點小:LCA 在左子樹。
  • 都比目前節點大:LCA 在右子樹。
  • 否則它們分在兩邊、或其中一個就是目前節點:目前節點就是 LCA。

我的嘗試
#

遞迴版本很快就 AC 了。之後想改成迭代,第一版忘了寫 while 迴圈,只往下走一步就結束、沒有回傳值;第二版少了冒號。11 月重寫時又出現變數沒定義和取 None 屬性的錯。

正確解法
#

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        node = root
        while True:
            if p.val < node.val and q.val < node.val:
                node = node.left
            elif p.val > node.val and q.val > node.val:
                node = node.right
            else:
                return node

複雜度
#

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

要特別避免的錯誤
#

  • 其中一個節點就是另一個的祖先時,答案是那個祖先自己,條件要包含等於。

面試口說整理
#

我從根往下走:兩個都比較小就往左,都比較大就往右,其他情況代表在這裡分岔或其中一個就是自己,回傳目前節點。時間 O(h)、空間 O(1)。

相關文章

LeetCode 226: Invert Binary Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 226 解題筆記:每個節點交換左右小孩;用同時指定,避免先改掉的那邊被拿來用
LeetCode 145: Binary Tree Postorder Traversal
·1 分鐘
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 145 解題筆記:迭代的後序遍歷,節點第一次彈出時標記後放回去,再依序推右、左小孩;第二次彈出才記錄
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 100: Same Tree
·1 分鐘
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 100 解題筆記:兩邊都是空的才相同;一邊空一邊不空就不同;都不空時比值再遞迴比左右