Lowest Common Ancestor

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.

  1. u, v are lca‘s descendant
    (each node can be a descendant of itself)
  2. 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

相關例題

Last Updated on 2023/09/12 by A1go

目錄
Bitnami