Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LCA implementation (fixes #89) #91

Merged
merged 12 commits into from
Oct 15, 2019
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* Lowest Common Ancestor in a Binary Search Tree.
*
* 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.
*/

function lca(node, n1, n2) {
if (node == null)
return null;

// If both n1 and n2 are smaller than root, then LCA lies in left
if (node.data > n1 && node.data > n2)
return lca(node.left, n1, n2);

// If both n1 and n2 are greater than root, then LCA lies in right
if (node.data < n1 && node.data < n2)
return lca(node.right, n1, n2);

return node;
}

module.exports = {
lca,
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const { lca } = require('.');

describe('LCA', () => {
it('Should return 12', () => {
expect(
lca(
{"left":{"left":{"data":4},"right":{"left":{"data":10},"right":{"data":14},"data":12},"data":8},"right":{"data":22},"data":20}
, 10
, 14)
.data).toEqual(12);
});
});