We can solve this using the approaches to find LCA in a binary tree.
But, binary search tree's property could be utilized, to come up with a better algorithm.
Lets review properties of a BST:
- Left subtree of a node N contains nodes whose values are lesser than or equal to node N's value.
- Right subtree of a node N contains nodes whose values are greater than node N's value.
- Both left and right subtrees are also BSTs.
Approach 1: Recursive Approach
Lowest common ancestor for two nodes
q would be the last ancestor node common to both of them. Here
last is defined in terms of the depth of the node. The below diagram would help in understanding what
Note: One of
q would be in the left subtree and the other in the right subtree of the LCA node.
Following cases are possible:
- Start traversing the tree from the root node.
- If both the nodes
qare in the right subtree, then continue the search with right subtree starting step 1.
- If both the nodes
qare in the left subtree, then continue the search with left subtree starting step 1.
- If both step 2 and step 3 are not true, this means we have found the node which is common to node
q's subtrees. and hence we return this common node as the LCA.
Time Complexity: , where is the number of nodes in the BST. In the worst case we might be visiting all the nodes of the BST.
Space Complexity: . This is because the maximum amount of space utilized by the recursion stack would be since the height of a skewed BST could be .
Approach 2: Iterative Approach
The steps taken are also similar to approach 1. The only difference is instead of recursively calling the function, we traverse down the tree iteratively. This is possible without using a stack or recursion since we don't need to backtrace to find the LCA node. In essence of it the problem is iterative, it just wants us to find the split point. The point from where
q won't be part of the same subtree or when one is the parent of the other.
Time Complexity : , where is the number of nodes in the BST. In the worst case we might be visiting all the nodes of the BST.
Space Complexity : .
Analysis written by: @godayaldivya.