題目出處
236. Lowest Common Ancestor of a Binary Tree
難度
medium
題目分類
Tree, Depth-First Search, Binary Tree
2026-09-29 二刷
個人範例程式碼 - 二刷 (2026/09/29)
# 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 root is None or root is p or root is q: # found or leaf (base case)
return root
left = self.lowestCommonAncestor(root.left, p, q) # search until found then up
right = self.lowestCommonAncestor(root.right, p, q) # search until found then up
if left and right: # found from two sons
return root
return left or right # return if found, or both not found
算法說明
經典的 LCA 重要題型,建議要背(或習慣)。
- 透過回傳代表下方子樹的狀態,分為「左邊找到」「右邊找到」「都沒找到」三種情況。
- 透過遞迴的特性,一路向下搜尋,找到了就會回傳(不用擔心沒找到)。
3.1. 判斷如果同時從 left or right 分別找到,那 root 就是 LCA。
3.2. 重點:由於找到其中一個 (如p) 就會提前回傳,另外一個 (如q) 必定存在於另一側或子孫中。
也就是說,如果另外一側找不到,則必定在子孫中。(可以推敲一下這句話)
細節:建議使用 is None, is p, is q,因為 eq (也就是 ==) 是可以被複寫的
雖然這裡兩個都沒問題,但 is 語意會更精準。
Time Complexity
O(n) # 接近遍歷所有樹
Space Complexity
O(h) # 用於儲存遞迴的深度,就是樹高 h
2022-04-21 一刷
個人範例程式碼 - 一刷 (2022/04/21)
# 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':
return self.lca(root, p, q)
def lca(self, root, p, q):
if not root:
return None
if root <mark> p or root </mark> q:
return root
# divide
found_left = self.lca(root.left, p, q)
found_right = self.lca(root.right, p, q)
# conquer
if found_left is not None and found_right is not None:
return root
elif found_left:
return found_left
elif found_right:
return found_right
else: # not found
return None
算法說明
這已經是系列題目的第三題了,前面可參考
- 此系列題目的第一題,由於設計上多了 parent node,相對來說比較沒有考到 LCA 的經常考點:
- 此系列題目的第二題,BST 與 BT 只多了比較好找數字,基本上有正確實作 LCA 其實也不用管數字排序:
LCA 的基本寫法,非常重要的題目。
拆成四路分析,左右返回是否有找到 A or B
討論 case 如下
- 如果兩側各返回 found,表示一邊各找到一個,此 node 即為答案
- 如果只有 left/right 返回 found,表示已經在下層找到答案,正在往上回傳。
- 如果都沒有 found,表示目前往下還找不到,返回 None
而特殊的 case 為
當 A 為 root,而 B 在此 root 之下,或相反的情況,
此時我們做的處理為返回 root,因為兩者的交集就是在 root 是兩者同時的 LCA。
最近在練習程式碼本身就可以自解釋的 Coding style,可以嘗試直接閱讀程式碼理解