236. Lowest Common Ancestor of a Binary Tree
題目網址:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/
題意:給一 BT 和兩 node
p
和q
, 找出他們的 lowest common ancestor(LCA)T
。
Solution:
想法:利用 DFS, 主要分成以三種情形:
- 無法在左子樹找到任何 target node, 代表 LCA 不可能在左子樹中, 因此 return 右子樹的結果。
- 無法在右子樹找到任何 target node, 代表 LCA 不可能在右子樹中, 因此 return 左子樹的結果。
- 若可分別在左右子樹中找到 target node, 代表 current root 為所求
e.g. 下圖中,
root = 1
,p = 4
,q = 10
- 以
2
為 root 時進行遞迴:
- left:return 4
- right:return 10
- 以
1
為 root 時進行遞迴:
- left:return 2 (因為其 left, right 皆非 null)
- right:return null
➔ 故最後答案為 2
class Solution { |
- time:$O(n)$ ➔ 遍歷整個 BT
- space:$O(n)$ ➔ 遞迴深度不超過
n
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Zako's Blog!
評論