ToolMight Logo
EasyTrees & BSTBST Invariant TraversalDivide and Conquer

Lowest Common Ancestor of a Binary Search Tree

Locate the lowest common ancestor of nodes p and q inside a Binary Search Tree. Compare recursive BST branching against an O(1)-space iterative root-to-split walk.

Optimal Time
O(h)
Optimal Space
O(1)
Primary Pattern
BST Invariant Traversal
Visualizer
Open Interactive View →

Problem Statement

Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.

According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself)."

Examples & Constraints

Example 1
Input: root = [6, 2, 8, 0, 4, 7, 9, null, null, 3, 5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6 because 2 is in the left subtree and 8 is in the right subtree.
Example 2
Input: root = [6, 2, 8, 0, 4, 7, 9, null, null, 3, 5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
Constraints
  • The number of nodes in the tree is in the range [2, 10^5].
  • -10^9 <= Node.val <= 10^9
  • All Node.val are unique.
  • p != q
  • p and q will exist in the BST.

Pattern Recognition & Core Invariant

How to Spot This Pattern

Whenever LCA is queried inside a Binary Search Tree rather than an arbitrary tree, value ordering eliminates searching both subtrees and turns the problem into a single downward path.

Core Invariant

The lowest common ancestor is the first node visited from the root whose value lies inclusively between min(p.val, q.val) and max(p.val, q.val).

Solution Approaches & Complexity

ApproachTimeSpaceNotes
1. Recursive BST Invariant Search
O(h)O(h)Recursively descend left when both targets are smaller than root, right when both are larger, or return root as soon as paths diverge.
2. BST Invariant Split Point WalkOptimal
O(h)O(1)Start at the root and navigate downward. The first node where p and q diverge to opposite sides (or where the node equals p or q) is the Lowest Common Ancestor.

1. Recursive BST Invariant Search

TimeO(h)
SpaceO(h)

Recursively descend left when both targets are smaller than root, right when both are larger, or return root as soon as paths diverge.

Time ComplexityO(h)

Explores at most one node per level down to height h.

Space ComplexityO(h)

Call stack frames scale with tree height h (O(log n) balanced, O(n) skewed).

How It Works

Recursive Branch Pruning

Using the BST ordering invariant recursively mirrors binary search:

  1. If p.val < root.val && q.val < root.val: recurse on root.left.
  2. Else if p.val > root.val && q.val > root.val: recurse on root.right.
  3. Otherwise return root (paths split here or root equals p or q).

Step-by-Step Dry Run

Execution Trace·Step 1 of 2
1Check p=2, q=4 at Root (6)

Both 2 < 6 and 4 < 6 hold, so recurse strictly into left subtree rooted at 2.

State:call LCA(node 2)
Strengths
  • +Clean 6-line recursive expression
  • +Natural BST divide-and-conquer formulation
Trade-offs
  • -Consumes O(h) recursion stack frames instead of O(1) space

Reference Implementation

Complete implementation for Recursive BST Invariant Search in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
def lowest_common_ancestor_rec(root, p, q):
if p.val < root.val and q.val < root.val:
return lowest_common_ancestor_rec(root.left, p, q)
if p.val > root.val and q.val > root.val:
return lowest_common_ancestor_rec(root.right, p, q)
return root

2. BST Invariant Split Point Walk

Optimal
TimeO(h)
SpaceO(1)

Start at the root and navigate downward. The first node where p and q diverge to opposite sides (or where the node equals p or q) is the Lowest Common Ancestor.

Time ComplexityO(h)

We descend one level per iteration. At most H steps are taken where H is tree height: O(log n) for balanced BST, O(n) for skewed BST.

Space ComplexityO(1)

Operates iteratively with a single pointer variable. Zero extra call stack memory allocated.

How It Works

The Power of Binary Search Tree Properties

In a general binary tree, finding LCA requires searching both branches exhaustively with post-order traversal.

However, a Binary Search Tree (BST) satisfies strict ordering:

  • All values in the left subtree are strictly smaller than root.val.
  • All values in the right subtree are strictly greater than root.val.

The Three Decision Cases:

Starting at curr = root:

  1. Both nodes are smaller: If p.val < curr.val and q.val < curr.val, then both p and q must reside exclusively in the left subtree. Move curr = curr.left.
  2. Both nodes are larger: If p.val > curr.val and q.val > curr.val, then both p and q must reside exclusively in the right subtree. Move curr = curr.right.
  3. The Split Point: If one value is on the left and the other is on the right (or if curr.val equals p.val or q.val), curr is the highest point where their paths divide! This curr node is guaranteed to be the Lowest Common Ancestor.

Iterative vs Recursive

This decision path is a single downward walk through the tree height. We can implement it iteratively in O(1) auxiliary space with zero recursion call stack overhead!

Step-by-Step Dry Run

Execution Trace·Step 1 of 3
1Start at Root (6)

Target p = 2, q = 8. Check: 2 < 6, but 8 > 6. One node is smaller, one is greater!

State:Split detected at node 6 -> LCA is 6
Strengths
  • +Optimal O(1) auxiliary space when implemented iteratively
  • +Leverages BST property to avoid traversing unnecessary subtrees
Trade-offs
  • -Relies on the BST sorted invariant; does not apply directly to general binary trees

Reference Implementation

Complete implementation for BST Invariant Split Point Walk in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def lowest_common_ancestor(root: TreeNode | None, p: TreeNode, q: TreeNode) -> TreeNode | None:
curr = root
while curr:
if p.val < curr.val and q.val < curr.val:
curr = curr.left
elif p.val > curr.val and q.val > curr.val:
curr = curr.right
else:
return curr
return None
if __name__ == "__main__":
# Tree: [6, 2, 8, 0, 4, 7, 9]
root = TreeNode(6)
root.left = TreeNode(2, TreeNode(0), TreeNode(4))
root.right = TreeNode(8, TreeNode(7), TreeNode(9))
p = root.left # node 2
q = root.right # node 8
lca = lowest_common_ancestor(root, p, q)
print("LCA value:", lca.val if lca else "None")
Interactive Visualizer

Trace Binary Search Tree mechanics in memory

Step through custom inputs in the Binary Search Tree visualizer to inspect pointer updates, array shifts, and call-stack state alongside Lowest Common Ancestor of a Binary Search Tree.

Open Binary Search Tree visualizer

Frequently Asked Questions

Why does this simple split condition guarantee the lowest common ancestor?

If p lies in the left subtree (p.val < curr.val) and q in the right (q.val > curr.val), no descendant of curr can contain both nodes, so curr is the lowest common ancestor.

Can a node be its own ancestor?

Yes. By standard LCA definition, a node counts as a descendant of itself, so whenever curr reaches p or q, descending stops and curr is returned.

Why prefer iterative descent over recursion here?

Because BST search follows a single linear chain with zero backtracking, replacing recursion with a while loop removes call-stack overhead (O(1) space) and avoids overflow on skewed trees of size 10^5.

Edge Cases & Implementation Pitfalls

Boundary Test Cases to Verify

  • Self-ancestor case (p = 2, q = 4 where 4 sits under 2): returns 2 immediately upon reaching curr == p.
  • Order-agnostic input (p = 8, q = 2 vs p = 2, q = 8): checking both inequalities handles p.val > q.val identically.
  • Degenerate skewed BST of 10^5 nodes: iterative O(1)-space descent avoids recursion stack overflow.

Common Bugs to Avoid

  • Running O(n) general Binary Tree LCA across both left and right children when BST ordering narrows every step to O(h).
  • Assuming p.val < q.val without comparing both ways (`p < curr && q < curr`, `p > curr && q > curr`).
  • Forgetting that a node counts as its own descendant (if curr equals p or q, stop descending and return curr).

Interview Follow-Up Variations

  • Lowest Common Ancestor of a general Binary Tree (no BST invariant): use post-order DFS returning matching subtrees.
  • LCA when p or q might not exist in the tree: verify existence or search all the way before concluding.

Related Problems

All problems
EasyTrees & BST

Maximum Depth of Binary Tree

Compute the maximum depth (node count along longest root-to-leaf path) of a binary tree using recursive post-order DFS and iterative level-order BFS.

Pattern: Depth-First Search (DFS)
O(n) · O(h)
Solve
EasyTrees & BST

Invert Binary Tree

Mirror a binary tree around its vertical axis by swapping left and right child pointers via recursive DFS or iterative level-order BFS.

Pattern: DFS Traversal
O(n) · O(h)
Solve
EasyTrees & BST

Subtree of Another Tree

Check whether subRoot matches an entire subtree of root in structure and values. Compare double-DFS tree matching against O(n + m) pre-order serialization + substring search.

Pattern: Tree Traversal DFS
O(n * m) · O(h)
Solve