Skip to problem
←

Lowest Common Ancestor of a Binary Tree

Medium 0 attempts

Given the root of a binary tree and two distinct node values p and q, return the value of their lowest common ancestor (LCA). All node values are unique, and both targets exist in the tree.

The LCA is the deepest node with both targets among its descendants. A node counts as its own descendant: if one target is an ancestor of the other, return that target’s value.

The tree is not necessarily a BST; numerical comparisons do not tell you which subtree contains a target.

Function contract

Implement lowestCommonAncestorOfABinaryTree(root, p, q). The editor converts the level-order root array (null marks missing children) into nodes with val, left, and right. p and q are integer values, not node objects.

Output: Return the integer value of the lowest common ancestor, not a node object.

Example 1

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

Example 2

Input
root = [3,5,1,6,2,0,8,null,null,7,4]
p = 5
q = 4
Output
5
Visual Aid
The deepest shared ancestor is 5
Targets 6 and 2 have lowest common ancestor 53516p2q08LCA

For this tree, p = 6 and q = 2. Both are below 5; neither target is an ancestor of the other. Return 5.

Constraints
  • 2 <= number of nodes <= 10^5
  • -10^9 <= Node.val <= 10^9
  • All values are unique
  • p and q are distinct values present in the tree

Parent Map

Record each node’s parent. Mark all ancestors of p, then walk from q toward the root until the first marked ancestor is reached.

javascript
function lowestCommonAncestorOfABinaryTree(root, p, q) {
  const parent = new Map([[root, null]]),
    stack = [root];
  let pn, qn;
  while (stack.length) {
    const node = stack.pop();
    if (node.val === p) pn = node;
    if (node.val === q) qn = node;
    for (const child of [node.left, node.right])
      if (child) {
        parent.set(child, node);
        stack.push(child);
      }
  }
  const ancestors = new Set();
  while (pn) {
    ancestors.add(pn);
    pn = parent.get(pn);
  }
  while (!ancestors.has(qn)) qn = parent.get(qn);
  return qn.val;
}

Time: O(n) | Space: O(n) auxiliary space, excluding output

Loading discussion…

Saved in this browser only. Private to you.

JavaScript