Lowest Common Ancestor · GeekWorkCode/AlgorithmVisualizer@5a836cd · GitHub
Skip to content

Commit 5a836cd

Browse files
author
Komal Dua
committed
Lowest Common Ancestor
1 parent 621165c commit 5a836cd

4 files changed

Lines changed: 74 additions & 2 deletions

File tree

algorithm/category.json

Lines changed: 3 additions & 2 deletions
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
function lcaBT (parent, root, a, b) {
2+
logger._print ('Beginning new Iteration of lcaBT () with parent: ' + parent + ', current root: ' + root);
3+
if (root === -1) {
4+
logger._print ('Reached end of path & target node(s) not found')
5+
return null;
6+
}
7+
8+
if (parent !== null) treeTracer._visit (root, parent)._wait ();
9+
else treeTracer._visit (root)._wait ();
10+
11+
if (root === a || root === b) return root;
12+
13+
var left = lcaBT (root, T [root] [0], a, b);
14+
var right = lcaBT (root, T [root] [1], a, b);
15+
16+
if (left !== null && right !== null) return root;
17+
if (left === null && right === null) {
18+
treeTracer._leave (root, parent)._wait ();
19+
}
20+
21+
return (left !== null ? left : right);
22+
}
23+
24+
var a = 7, b = 9;
25+
logger._print ('Lowest common ancestor of ' + a + ' & ' + b + ' is: ' + lcaBT (null, 5, a, b));
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
var G = [ // G[i][j] indicates whether the path from the i-th node to the j-th node exists or not
2+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
3+
[1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
4+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
5+
[0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0],
6+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
7+
[0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0],
8+
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
9+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
10+
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1],
11+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
12+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
13+
];
14+
15+
16+
var T = [ // mapping to G as a binary tree , [i][0] indicates left child, [i][1] indicates right child
17+
[-1,-1],
18+
[ 0, 2],
19+
[-1,-1],
20+
[ 1, 4],
21+
[-1,-1],
22+
[ 3, 8],
23+
[-1, 7],
24+
[-1,-1],
25+
[ 6,10],
26+
[-1,-1],
27+
[ 9,-1]
28+
];
29+
30+
var treeTracer = new DirectedGraphTracer( " Traversal Pre-order ")._setTreeData ( G, 5 );
31+
var logger = new LogTracer ( " Log ");
Lines changed: 15 additions & 0 deletions

0 commit comments

Comments
 (0)