本文完整拆解 LeetCode 235 Lowest Common Ancestor of a Binary Search Tree 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Lowest Common Ancestor of a Binary Search Tree 一次弄懂。
Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link
Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
Example 1:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 Output: 6 Explanation: The LCA of nodes 2 and 8 is 6.
Example 2:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 Output: 2 Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
Example 3:
Input: root = [2,1], p = 2, q = 1 Output: 2
Constraints:
- The number of nodes in the tree is in the range
[2, 105]. -109 <= Node.val <= 109- All
Node.valare unique. p != qpandqwill exist in the BST.
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if p.val < root.val and q.val < root.val:
return self.lowestCommonAncestor(root.left, p, q)
if p.val > root.val and q.val > root.val:
return self.lowestCommonAncestor(root.right, p, q)
return root
Lowest Common Ancestor of a Binary Search Tree 解題思路
利用 BST 的有序性可以把問題變得非常簡單:如果兩個目標值都小於目前節點,答案一定在左子樹;都大於就在右子樹;只要出現「一邊小一邊大」或「其中一個等於目前節點」,目前節點就是最近共同祖先。完全不需要回溯或額外記錄路徑。
Lowest Common Ancestor of a Binary Search Tree 演算法步驟
- 從 root 開始,令 current = root。
- 若 p.val 與 q.val 都小於 current.val,往左走。
- 若兩者都大於 current.val,往右走。
- 否則目前節點就是分岔點,回傳 current。
Lowest Common Ancestor of a Binary Search Tree 複雜度分析
| 項目 | 複雜度 |
|---|---|
| 時間複雜度 | O(h) |
| 空間複雜度 | O(1) |
每一步都往下走一層,時間為樹高 O(h),平衡時 O(log n)。迭代版不需要堆疊,空間為 O(1);遞迴版則是 O(h)。
Lowest Common Ancestor of a Binary Search Tree 的邊界情況與常見錯誤
- p 或 q 本身可能就是另一個的祖先,此時答案就是那個祖先節點。
- 題目保證兩個節點都存在於樹中,否則需額外驗證。
- 這個解法只對 BST 成立;一般二元樹要用後序遞迴版本。
- 不要用一般樹的通解去做,會浪費 BST 的有序性。
Lowest Common Ancestor of a Binary Search Tree 其他解法比較
| 解法 | 時間 | 空間 | 說明 |
|---|---|---|---|
| 記錄兩條根到節點的路徑再比對 | O(h) | O(h) | 通用但要額外存路徑 |
| 一般二元樹的後序遞迴解 | O(n) | O(h) | 正確但沒利用 BST 性質 |
| 利用 BST 性質迭代下行 | O(h) | O(1) | 本文採用 |
