Lowest Common Ancestor in a Binary Search Tree

Binary Search Tree

A binary search tree is a type of a binary tree where all the values smaller than any node are present in its left subtree, and all the values greater than it are present at the right subtree.

Problem statement

We are given the root node of the binary search tree and two integer values, n and m. Our task is to return the lowest common ancestor present of both the nodes in the binary search tree.

For example:

Lowest Common Ancestor in a Binary Search Tree

In the above example, we have a binary search tree, and we will find out the lowest common ancestors of some nodes.

  1. n=6 and m=15, then the lowest common ancestor is 12
  2. n=4 and m=22, then the lowest common ancestor is 12
  3. n=7 and m=9, then the lowest common ancestor is 9

Approach 1

We will find out the root to node1 path and root to node2 path and store it into ArrayList. Now the first common element of the ArrayList will be the lowest common ancestor.

Java code:

Output:

Lowest Common Ancestor in a Binary Search Tree

Time complexity: O(H)+O(H), where H is the height of the tree. In the worst case, it can be upto O(N).

Space complexity: O(N)+O(N) in the worst case.

Method 2

We will use recursion to get the lowest common ancestor of the nodes.

  • In the recursive call, if the current node is equal to node1 or node2, then the current node will be LCS.
  • If the value of the current node is lesser than a node and greater than the other node then the current node will be LCS.
  • If the value of the current node is lesser than the value of both the nodes then the answer will lie in the right subtree of the current node.
  • If the value of the current node is greater than the value of both the nodes, then the answer will lie in the left subtree of the current node.

Java code:

Output:

Lowest Common Ancestor in a Binary Search Tree

Time complexity: O(N) in the worst case; otherwise, O(H) where H is the height.

Space complexity: O(H) auxiliary recursion space stack.

Method 3

This approach is the iterative approach of the above solution. It will help us to save the auxiliary stack space occupied by the recursion.

Java code:

Output:

Lowest Common Ancestor in a Binary Search Tree

Time complexity: O(H) where H is the height of the tree which can be N in the worst case.

Space complexity: O(1) because no auxiliary space is used.