Given the root of a Binary Search Tree and two node n1 and n2, find the Lowest Common Ancestor (LCA). LCA is the deepest node that has both n1 and n2 as descendants.
Note: Both node are always present in the Binary Search Tree.
[Naive Approach] LCA by Normal Binary Tree Methods - O(n) Time and O(n) Space
We can use any of the approaches discussed in Lowest Common Ancestorin a Binary Tree, which run in O(n) time, where n is the number of nodes in the BST. However, we can achieve a better time complexity by leveraging the properties of the BST.
[Better Approach] Using BST Properties (Recursive Approach) - O(h) Time and O(h) Space
This approach is based on the observation that the LCA is the lowest (closest to root) node whose value lies between n1 and n2.
In a Binary search tree, while traversing the tree from top to bottom the first node which lies in between the two numbers n1 and n2 is the LCA of the nodes, i.e. the first node n with the lowest depth which lies in between n1 and n2 (n1 <= n <= n2, assuming n1 < n2).
So, we just recursively traverse the BST , if node's value is greater than both n1 and n2 then our LCA lies in the left side of the node, if it is smaller than both n1 and n2, then LCA lies on the right side. Otherwise, the root is LCA (assuming that both n1 and n2 are present in BST).
Output
8
[Expected Approach] Using BST Properties (Iterative Method) - O(h) Time and O(1) Space
The auxiliary space in the above method can be optimized by eliminating recursion. Below is the iterative implementation of this approach.