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

Method GetLCA

graph/lowestcommonancestor.go:61–84  ·  view source on GitHub ↗
(u, v int)

Source from the content-addressed store, hash-verified

59}
60
61func (tree *Tree) GetLCA(u, v int) int {
62 if tree.GetDepth(u) < tree.GetDepth(v) {
63 u, v = v, u
64 }
65
66 for j := tree.MAXLOG - 1; j >= 0; j-- {
67 if tree.GetDepth(tree.jump[j][u]) >= tree.GetDepth(v) {
68 u = tree.jump[j][u]
69 }
70 }
71
72 if u == v {
73 return u
74 }
75
76 for j := tree.MAXLOG - 1; j >= 0; j-- {
77 if tree.jump[j][u] != tree.jump[j][v] {
78 u = tree.jump[j][u]
79 v = tree.jump[j][v]
80 }
81 }
82
83 return tree.jump[0][u]
84}
85
86func NewTree(numbersVertex, root int, edges []TreeEdge) (tree *Tree) {
87 tree = new(Tree)

Callers 1

TestLCAFunction · 0.95

Calls 1

GetDepthMethod · 0.95

Tested by 1

TestLCAFunction · 0.76