Given a BST and two nodes x and y in it, find the lowest common ancestor (LCA) of x and y. The solution should return null if either x or y is not the actual node in the tree.

The lowest common ancestor (LCA) of two nodes x and y in the BST is the lowest (i.e., deepest) node that has both x and y as descendants, where each node can be a descendant of itself (so if x is reachable from w, w is the LCA). In other words, the LCA of x and y is the shared ancestor of x and y that is located farthest from the root.

 
For example, consider the following BST:

LCA of two nodes in the BST

Practice this problem

A simple solution would be to store the path from root to x and the path from the root to y in two auxiliary arrays. Then traverse both arrays simultaneously till the values in the arrays match. The last matched value will be the LCA. If the end of one array is reached, then the last seen value is LCA. The time complexity of this solution is O(n) for a binary search tree with n nodes. However, it requires O(n) auxiliary space for storing two arrays.

Recursive Version

We can recursively find the lowest common ancestor of nodes x and y present in the BST. The trick is to find the BST node, which has one key present in its left subtree and the other key present in the right subtree. If any such node is present in the tree, then it is LCA; if y lies in the subtree rooted at node x, then x is the LCA; otherwise, if x lies in the subtree rooted at node y, then y is the LCA.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

LCA is 10

Java


Download  Run Code

Output:

LCA is 10

Python


Download  Run Code

Output:

LCA is 10

The time complexity of the above solution is O(n), where n is the size of the BST, and requires space proportional to the tree’s height for the call stack.

Iterative Version

The same algorithm can be easily implemented iteratively. Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Output:

LCA is 10

Java


Download  Run Code

Output:

LCA is 10

Python


Download  Run Code

Output:

LCA is 10

The time complexity of the above solution is O(n), where n is the size of the BST. The auxiliary space required by the program is O(1).

 
References: https://en.wikipedia.org/wiki/Lowest_common_ancestor