Skip to content

lcaBinaryLifting ​

lcaBinaryLifting(adj: usize[][], root: usize): Lca builds binary lifting tables over the undirected tree described by the adjacency list adj, where adj[v] holds the neighbors of vertex v and root anchors every query. The returned Lca is an owned handle of tyrus:algorithm; it exposes query(u, v), which returns the lowest common ancestor of vertices u and v in O(log n) with binary lifting.

Construction ​

SyntaxDescription
lcaBinaryLifting(adj: usize[][], root: usize)Build LCA tables over the tree adj, rooted at root

Methods ​

MethodSignatureReturnsDescription
query(u: usize, v: usize)usizeLowest common ancestor of vertices u and v

Complexity ​

OperationTime Complexity
constructionO(n log n), binary lifting tables
queryO(log n)
memoryO(n log n)

Examples ​

balanced tree ​

tyrus
import { lcaBinaryLifting } from "tyrus:algorithm";

const adj: usize[][] = [[1, 2], [0, 3, 4], [0, 5, 6], [1], [1], [2], [2]];
const lca = lcaBinaryLifting(adj, 0);

print(lca.query(3, 4));  // 1
print(lca.query(5, 6));  // 2
print(lca.query(3, 6));  // 0

deep path ​

tyrus
import { lcaBinaryLifting } from "tyrus:algorithm";

const path: usize[][] = [[1], [0, 2], [1, 3], [2, 4], [3, 5], [4, 6], [5, 7], [6, 8], [7, 9], [8]];
const lca = lcaBinaryLifting(path, 0);

print(lca.query(9, 1));  // 1
print(lca.query(9, 8));  // 8
print(lca.query(0, 9));  // 0

single vertex ​

tyrus
import { lcaBinaryLifting } from "tyrus:algorithm";

const single: usize[][] = [[]];
const lca = lcaBinaryLifting(single, 0);

print(lca.query(0, 0));  // 0

namespace import ​

tyrus
import * as alg from "tyrus:algorithm";

const lca = alg.lcaBinaryLifting([[1], [0, 2], [1]], 0);
print(lca.query(1, 2));  // 1
print(lca.query(0, 2));  // 0