Skip to content

LCA implementation (fixes #89) #91

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

Merged
merged 12 commits into from
Oct 15, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.value > n1 && node.value > n2)
return lca(node.leftChild, n1, n2);

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

return node;
}

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

// Quick JSON equivalent
// {"left":{"left":{"data":4},"right":{"left":{"data":10},"right":{"data":14},"data":12},"data":8},"right":{"data":22},"data":20}

describe('LCA', () => {

let bst = new BinarySearchTree(20);
bst.add(22);
bst.add(8);
bst.add(12);
bst.add(4);
bst.add(14);
bst.add(10);

it('Should return 12', () => {
expect(lca(bst.root, 10, 14).value).toEqual(12);
});

it('Should return 8', () => {
expect(lca(bst.root, 14, 8).value).toEqual(8);
});

it('Should return 20', () => {
expect(lca(bst.root, 10, 22).value).toEqual(20);
});
});