150強訪談簡單

BST 最低的共同祖先

「BST 最低共同祖先」問題的詳細指南和 Python 實作。

問題陳述

簡單

給定二元搜尋樹 (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

範例

Example 1
Input
[6,2,8,0,4,7,9,None,None,3,5], 2, 8
Output
6
Explanation

The LCA of nodes 2 and 8 is 6, which is the root.

Example 2
Input
[6,2,8,0,4,7,9,None,None,3,5], 2, 4
Output
2
Explanation

The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself.

Example 3
Input
[2,1], 2, 1
Output
2
Explanation

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.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。