VOOZH about

URL: https://www.geeksforgeeks.org/dsa/lowest-common-ancestor-in-a-binary-search-tree/

⇱ Lowest Common Ancestor in a Binary Search Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Lowest Common Ancestor in a Binary Search Tree

Last Updated : 11 Oct, 2025

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.

Examples:

Input:  n1.data = 4, n2.data = 14

👁 lowest_common_ancestor_in_a_binary_tree2

Output: 8
Explanation: 8 is the lowest common ancestor (LCA) of nodes 4 and 14, as it is the deepest node that is an ancestor of both.

👁 lowest_common_ancestor_in_a_binary_tree_2

Input: n1.data = 10, n2.data = 14

👁 lowest_common_ancestor_in_a_binary_tree2

Output: 12
Explanation: 12 is the lowest common ancestor (LCA) of nodes 10 and 14, as it is the deepest node that is an ancestor of both.

👁 lowest_common_ancestor_in_a_binary_tree_4

[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.


Output
8

Related Articles:
LCA using Parent Pointer
Find LCA in Binary Tree using RMQ

Comment