MCPcopy
hub / github.com/TheAlgorithms/Go / LowestCommonAncestor

Function LowestCommonAncestor

graph/lowestcommonancestor.go:113–123  ·  view source on GitHub ↗

For each node, we will precompute its ancestor above him, its ancestor two nodes above, its ancestor four nodes above, etc. Let's call `jump[j][u]` is the `2^j`-th ancestor above the node `u` with `u` in range `[0, numbersVertex)`, `j` in range `[0,MAXLOG)`. These information allow us to jump from a

(tree *Tree)

Source from the content-addressed store, hash-verified

111// Let's call `jump[j][u]` is the `2^j`-th ancestor above the node `u` with `u` in range `[0, numbersVertex)`, `j` in range `[0,MAXLOG)`.
112// These information allow us to jump from any node to any ancestor above it in `O(MAXLOG)` time.
113func LowestCommonAncestor(tree *Tree) {
114 // call dfs to compute depth from the root to each node and the parent of each node.
115 tree.dfs(tree.root, tree.root)
116
117 // compute jump[j][u]
118 for j := 1; j < tree.MAXLOG; j++ {
119 for u := 0; u < tree.numbersVertex; u++ {
120 tree.jump[j][u] = tree.jump[j-1][tree.jump[j-1][u]]
121 }
122 }
123}

Callers 2

TestLCAFunction · 0.85
TestLCAWithLargeTreeFunction · 0.85

Calls 1

dfsMethod · 0.65

Tested by 2

TestLCAFunction · 0.68
TestLCAWithLargeTreeFunction · 0.68