Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Lowest Common Ancestor in BST

Medium Acceptance 70.5% Points 30

You are given the root of a Binary Search Tree (BST) and two node values p and q. Your task is to find and return the value of their Lowest Common Ancestor (LCA).

The Lowest Common Ancestor of two nodes is the lowest node in the tree that has both nodes as descendants (where a node can be a descendant of itself).

Examples
Example 1

image Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: Node 6 is the lowest common ancestor of nodes 2 and 8.

Example 2

image Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: Node 2 is an ancestor of node 4, so it is the lowest common ancestor.

Example 3

image Input: root = [2,1], p = 2, q = 1
Output: 2
Explanation: The root node is the lowest common ancestor.

Constraints
    • 1 = Number of nodes = 105
    • -10? = Node.data = 10?
Hints
  • Using the BST property:
    • If both p and q are smaller than the current node, move to the left subtree.
    • If both p and q are greater than the current node, move to the right subtree.
    • Otherwise, the current node is the **Lowest Common Ancestor
Topics
Tree Traversal Binary Tree
Companies
Apple Sprinklr Media.net
Added 08 Aug 2026 70.5% acceptance
Ln 1, Col 1Sign in to save your code
50 30 70 20 40 60 80
20 40
30