Lowest Common Ancestor
- 2023.07.23
- Binary Lifting Data Structure Lowest Common Ancestor Tree
The lowest common ancestor (LCA) (also called least common ancestor) of two nodes u
and v
in a tree or directed acyclic graph (DAG) T
is the lowest (i.e. deepest) node that has both v and w as descendants.
u
,v
arelca
‘s descendant
(each node can be a descendant of itself)- path_from_root_to_lca := [root, …, lca]
path_from_root_to_u := [root, …, u]
path_from_root_to_v := [root, …, v]path_from_root_to_lca ⊆ path_from_root_to_u and path_from_root_to_lca ⊆ path_from_root_to_v
(path_from_root_to_u – path_from_root_to_lca) ∩ (path_from_root_to_v – path_from_root_to_lca) = ∅
LCA in Binary Liftin
Binary Lifting
是一種 Bottom-UP 的 dynamic programming
假設要找node
的第k
個祖先
把k
拆成 k == k0 + k1 + k2 + … + kn, log2(ki) ∈ {0} ∪ ℕ, ki > ki + 1
要花 O(n) 的 time/space complexity 建立 table
(dp[i][node] := node 的第 2 ** i 個祖先)
但搜尋node
的第k
個祖先只需要 O(log(k)) 的 time complexity
相關例題
- Leetcode # 235. Lowest Common Ancestor of a Binary Search Tree
- Leetcode # 1483. ⭐️ Kth Ancestor of a Tree Node
- Leetcode # 1644. Lowest Common Ancestor of a Binary Tree II
- Leetcode # 2846. Minimum Edge Weight Equilibrium Queries in a Tree
Last Updated on 2023/09/12 by A1go