BST 最低的共同祖先
「BST 最低共同祖先」問題的詳細指南和 Python 實作。
1. 學習
「BST 的最低共同祖先」問題是樹部分的關鍵挑戰。
此實作著重於 Python 中的簡單層級邏輯。
在我們提供的解決方案中,我們優先考慮技術準確性和程式碼可讀性。
2. Real-World Applications
3. Visual Intuition
可視化 BST 最低公共祖先的邏輯流程。
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
仔細閱讀 BST 的最低共同祖先的問題陳述。
2. Formulate brute force
起草一個簡單的迭代解決方案。
3. Identify inefficiency
尋找冗餘計算。
4. Optimize search path
使用散列或排序來加速該過程。
5. Final Implementation
清理生產標準代碼。
問題陳述
給定二元搜尋樹 (BST),找出 BST 中兩個給定節點的最低公共祖先 (LCA) 節點。
根據 LCA 的定義:“最低公共祖先被定義為兩個節點 p 和 q 之間的最低公共祖先,作為 T 中同時具有 p 和 q 作為後代的最低節點(其中我們允許一個節點是其自身的後代)。”
BST 被表示為一個級別順序列表。實作一個函數 lowestCommonAncestor(root: list, p: int, q: int) -> int 傳回 LCA 節點的值。
- •The number of nodes in the tree is in the range [2, 100000]
- •-1000000000 <= Node.val <= 1000000000
- •All Node.val are unique
- •p != q
- •p and q will exist in the BST
範例
[6,2,8,0,4,7,9,None,None,3,5], 2, 8
6
The LCA of nodes 2 and 8 is 6, which is the root.
[6,2,8,0,4,7,9,None,None,3,5], 2, 4
2
The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself.
[2,1], 2, 1
2
The LCA of nodes 2 and 1 is 2.
Need a Hint?
Edge Cases to Watch
- 空輸入結構
- 單元素輸入
- 大數值範圍
準備好解決了嗎?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
面試見解和變化
複雜度分析分解
為什麼時間: Directly evaluates all possibilities.
為什麼選擇太空: Uses standard local memory.
為什麼時間: Optimized paths reduce total operations.
為什麼選擇太空: May trade memory for speed.
最佳化解決方案Python程式碼
最佳化解決方案Python程式碼
def lowest_common_ancestor_opt(root, p, q):
if isinstance(root, list):
r = build_tree(root)
val_p = p[0] if isinstance(p, list) else p
val_q = q[0] if isinstance(q, list) else q
def find_node(node, val):
if not node: return None
if node.val == val: return node
return find_node(node.left, val) or find_node(node.right, val)
node_p = find_node(r, val_p) or TreeNode(val_p)
node_q = find_node(r, val_q) or TreeNode(val_q)
res = lowest_common_ancestor_opt_helper(r, node_p, node_q)
return res.val if res else None
return lowest_common_ancestor_opt_helper(root, p, q)
def lowest_common_ancestor_opt_helper(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
curr = root
while curr:
if p.val > curr.val and q.val > curr.val:
curr = curr.right
elif p.val < curr.val and q.val < curr.val:
curr = curr.left
else:
return curr暴力破解代碼(劇透保護)
暴力破解代碼(劇透保護)
def lowest_common_ancestor_brute(root, p, q):
if isinstance(root, list):
r = build_tree(root)
val_p = p[0] if isinstance(p, list) else p
val_q = q[0] if isinstance(q, list) else q
def find_node(node, val):
if not node: return None
if node.val == val: return node
return find_node(node.left, val) or find_node(node.right, val)
node_p = find_node(r, val_p) or TreeNode(val_p)
node_q = find_node(r, val_q) or TreeNode(val_q)
res = lowest_common_ancestor_brute_helper(r, node_p, node_q)
return res.val if res else None
return lowest_common_ancestor_brute_helper(root, p, q)
def lowest_common_ancestor_brute_helper(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
if not root or root == p or root == q:
return root
left = lowest_common_ancestor_brute_helper(root.left, p, q)
right = lowest_common_ancestor_brute_helper(root.right, p, q)
if left and right:
return root
return left or rightAlgorithm Pattern Checklist
When dealing with Trees data patterns.
- Are constraints clear?
- Is there a linear or logarithmic optimization possible?
PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!
推薦的 Python 資源
透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。
Python 迴圈:For 與 While 迴圈解釋
了解如何使用 Python 循環來迭代資料。透過互動式範例掌握 for 迴圈、while 迴圈、break、continue 和迴圈最佳實務。
如何在 Python 中找到列表的長度
了解如何使用 len() 函數在 Python 中尋找清單的長度。了解 O(1) 時間複雜度和檢查計數。
Python 字串方法備忘單
Python 字串操作的完整參考指南。掌握格式化、搜尋、拆分、取代和檢查字串屬性。
Python 與 JavaScript:哪種程式語言最好?
Python 和 JavaScript 的全面比較。探索語法差異、效能、用例(後端與前端)和編碼範例。