diff --git a/src/_DataStructures_/Trees/BinarySearchTree/lowest-common-ancestor/index.js b/src/_DataStructures_/Trees/BinarySearchTree/lowest-common-ancestor/index.js new file mode 100644 index 00000000..30ef7ce9 --- /dev/null +++ b/src/_DataStructures_/Trees/BinarySearchTree/lowest-common-ancestor/index.js @@ -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, +}; diff --git a/src/_DataStructures_/Trees/BinarySearchTree/lowest-common-ancestor/index.test.js b/src/_DataStructures_/Trees/BinarySearchTree/lowest-common-ancestor/index.test.js new file mode 100644 index 00000000..25cf90d7 --- /dev/null +++ b/src/_DataStructures_/Trees/BinarySearchTree/lowest-common-ancestor/index.test.js @@ -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); + }); +});