TRT
Sign in
mediumCoreLeetCode#BST property#split point

Lowest common ancestor of a binary search tree

Find the lowest node that has both p and q as descendants, by walking down from the root until the two keys split.

The Runtime Theory Team1 min read
Taught inBinary search treesPro — members onlyA binary search tree keeps smaller keys to the left of each node and larger keys to the right, so a search discards a whole subtree at every step. Its speed depends entirely on its height.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inroot = [6, 2, 8, 0, 4, 7, 9, null, null, 3, 5], p = 2, q = 8

out6

insame tree, p = 2, q = 4

out2

inroot = [2, 1], p = 2, q = 1

out2

Given a binary search tree and two of its nodes, p and q, return their lowest common ancestor: the deepest node that has both as descendants (a node counts as its own descendant).

Before you code

In a general binary tree this needs a full traversal. In a BST, the keys tell you which way p and q lie at every node, so one downward walk suffices.

Hints

  1. If both p and q are smaller than the current node, the answer is in the left subtree; if both are larger, in the right.
  2. Otherwise they split here (or one of them is this node): this node is the answer.
  3. The walk is O(h) time and O(1) space if written as a loop.

Production & complexity notes

When solving Lowest common ancestor of a binary search tree on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Binary search trees to reinforce the underlying pattern.

What it practices

Using the search tree property to discard subtrees, from Binary search trees.

Not started

Sign in to save your learning progress.

Sign in to save