Skip to interview prep
Apexed

94. Lowest Common Ancestor in a Binary Tree

MediumTrees

Given a binary tree with distinct values and two values p and q that both appear in it, return the value of their lowest common ancestor: the deepest node that has both as descendants. A node counts as a descendant of itself.

The tree is not necessarily a search tree.

A binary tree is passed as TreeNode objects with val, left and right. The tests write trees in level order, with null for a missing child.

Example 1

Input: root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], p = 5, q = 4
Output: 5

Constraints

  • 2 ≤ nodes ≤ 10⁵
  • p ≠ q, and both exist in the tree

Tab indents · Ctrl/⌘ + Enter runs · Esc then Tab leaves the editor

Run checks these cases; the expected output comes from the reference solution. Submit judges all 5 hidden and sample tests.

Code runs only in your browser in an isolated sandbox. Progress and submissions are saved on this device.

Lowest Common Ancestor in a Binary Tree — coding interview practice — Apexed