Compute depth[v] for all nodes (BFS/DFS).\n\n Build the table.\n\n For query : if depth[a] < depth[b], swap them.\n\n Jump up to the same depth as : jump depth[a] - depth[b] steps.\n\n If , return (one is ancestor of the other).\n\n Binary search: for down to , if up[a][j] \!= up[b][j], jump both.\n\n Return up[a][0] (the LCA).\n\nThis runs in time and uses space.
Graph Theory37 sections · 1633 units
Open in CourseAlgorithm
(LCA with binary lifting)