Find the lowest common ancestor of two values in a BST
A pricing service stores product price points in a binary search tree. To find the narrowest price bracket that contains two prices, it needs the lowest node that has both of them in its subtree.
Implement lowestSharedAncestor(root, a, b). It returns the lowest node in the tree that is an ancestor of both the node holding a and the node holding b.
lowestSharedAncestor(root, a, b) // => node | null
{ value, left, right }. A missing child is null. An empty tree is null.left subtree are smaller and all values in its right subtree are larger.a is above the node holding b, the answer is the node holding a.a and b can be passed in either order, and they can be equal.result === someNode holds), not a copy or a value.a or b is not in the tree, return null.// 50
// / \
// 30 70
// / \ / \
// 20 40 60 80
// / \ \
// 35 45 65
lowestSharedAncestor(root, 20, 45); // => the node 30
lowestSharedAncestor(root, 35, 65); // => the node 50 (the root)
lowestSharedAncestor(root, 70, 65); // => the node 70 (70 is above 65)
lowestSharedAncestor(root, 40, 40); // => the node 40
lowestSharedAncestor(root, 33, 45); // => null (33 is not in the tree)
lowestSharedAncestor(null, 1, 2); // => null
Use the ordering of the tree instead of searching every node. Aim for O(h) time, where h is the height of the tree.