Skip to content

Commit 1387eef

Browse files
amahdyTheSTL
authored andcommitted
LCA implementation (fixes knaxus#89) (knaxus#91)
* Create solution file * Move to correct folder * Add the algorithm Ref: https://www.geeksforgeeks.org/lowest-common-ancestor-in-a-binary-search-tree/ * Add a test case * Fix test case * Fix test by adding missing arguments * Move to inside BST folder * Move to inside BST folder * Add more tests and use BST class * Fix variable declaration * Update reference * Match naming used in BST
1 parent d344e48 commit 1387eef

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* Lowest Common Ancestor in a Binary Search Tree.
3+
*
4+
* Given values of two values n1 and n2 in a Binary Search Tree, find the Lowest Common Ancestor (LCA). You may assume that both the values exist in the tree.
5+
*/
6+
7+
function lca(node, n1, n2) {
8+
if (node == null)
9+
return null;
10+
11+
// If both n1 and n2 are smaller than root, then LCA lies in left
12+
if (node.value > n1 && node.value > n2)
13+
return lca(node.leftChild, n1, n2);
14+
15+
// If both n1 and n2 are greater than root, then LCA lies in right
16+
if (node.value < n1 && node.value < n2)
17+
return lca(node.rightChild, n1, n2);
18+
19+
return node;
20+
}
21+
22+
module.exports = {
23+
lca,
24+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
const { lca } = require('.');
2+
const BinarySearchTree = require('../index');
3+
4+
// Quick JSON equivalent
5+
// {"left":{"left":{"data":4},"right":{"left":{"data":10},"right":{"data":14},"data":12},"data":8},"right":{"data":22},"data":20}
6+
7+
describe('LCA', () => {
8+
9+
let bst = new BinarySearchTree(20);
10+
bst.add(22);
11+
bst.add(8);
12+
bst.add(12);
13+
bst.add(4);
14+
bst.add(14);
15+
bst.add(10);
16+
17+
it('Should return 12', () => {
18+
expect(lca(bst.root, 10, 14).value).toEqual(12);
19+
});
20+
21+
it('Should return 8', () => {
22+
expect(lca(bst.root, 14, 8).value).toEqual(8);
23+
});
24+
25+
it('Should return 20', () => {
26+
expect(lca(bst.root, 10, 22).value).toEqual(20);
27+
});
28+
});

0 commit comments

Comments
 (0)