MCPcopy
hub / github.com/TheAlgorithms/JavaScript / getLCA

Method getLCA

Graphs/LCABinaryLifting.js:29–48  ·  view source on GitHub ↗
(node1, node2)

Source from the content-addressed store, hash-verified

27 }
28
29 getLCA(node1, node2) {
30 // We make sure that node1 is the deeper node among node1 and node2
31 if (this.depth.get(node1) < this.depth.get(node2)) {
32 ;[node1, node2] = [node2, node1]
33 }
34 // We check if node1 is the ancestor of node2, and if so, then return node1
35 const k = this.depth.get(node1) - this.depth.get(node2)
36 node1 = this.kthAncestor(node1, k)
37 if (node1 === node2) {
38 return node1
39 }
40
41 for (let i = this.log - 1; i >= 0; i--) {
42 if (this.up.get(node1).get(i) !== this.up.get(node2).get(i)) {
43 node1 = this.up.get(node1).get(i)
44 node2 = this.up.get(node2).get(i)
45 }
46 }
47 return this.up.get(node1).get(0)
48 }
49}
50
51function lcaBinaryLifting(root, tree, queries) {

Callers 1

lcaBinaryLiftingFunction · 0.95

Calls 2

kthAncestorMethod · 0.80
getMethod · 0.45

Tested by

no test coverage detected