Skip to content
DSA Patterns
Menu
Language
Tree DFSLC #2366 of 6← Previous

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Mediumtree-dfs

Lowest Common Ancestor of a Binary Tree

Problem (restated)

Given a binary tree and two nodes p and q, return their lowest common ancestor (deepest node that has both as descendants).

Intuition

Walk a root-to-node path to p and another to q; the LCA is the last node the two paths share. If either path is missing, the other node is the answer.

Approaches

Path alignment LCA

Unverified
Time O(n)Space O(h)

Idea. Build the path from the root to p and to q iteratively, then scan both from the start and keep the last matching node.

Walkthrough. Paths to p and q share only the root → root is LCA.

Trade-offs. Two path walks use O(h) space each and no parent map; recursive post-order is an alternative that also needs a stack.

Solution
Show helper code
export class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val = 0, left: TreeNode | null = null, right: TreeNode | null = null) {
    this.val = val; this.left = left; this.right = right;
  }
}
export class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val = 0, left: TreeNode | null = null, right: TreeNode | null = null) {
    this.val = val; this.left = left; this.right = right;
  }
}
type Step = [TreeNode | null, boolean];

function pathTo(root: TreeNode | null, target: TreeNode | null): TreeNode[] {
  // One path plus (node, processed) markers: O(h) space.
  const path: TreeNode[] = [];
  const stack: Step[] = [[root, false]];
  while (stack.length > 0) {
    const [node, processed] = stack.pop()!;
    if (processed) {
      path.pop();
      continue;
    }
    if (node === null) continue;
    if (node === target) return [...path, node];
    path.push(node);
    stack.push([node, true]);
    if (node.right !== null) stack.push([node.right, false]);
    if (node.left !== null) stack.push([node.left, false]);
  }
  return [];
}

export function lowestCommonAncestor(
  root: TreeNode | null,
  p: TreeNode | null,
  q: TreeNode | null,
): TreeNode | null {
  if (root === null) return null;
  const pathP = pathTo(root, p);
  const pathQ = pathTo(root, q);
  if (pathP.length === 0 || pathQ.length === 0) {
    if (pathP.length !== 0) return p;
    if (pathQ.length !== 0) return q;
    return null;
  }
  let lca: TreeNode | null = null;
  const n = Math.min(pathP.length, pathQ.length);
  for (let i = 0; i < n; i++) {
    if (pathP[i] !== pathQ[i]) break;
    lca = pathP[i];
  }
  return lca;
}
type Step = [TreeNode | null, boolean];

function pathTo(root: TreeNode | null, target: TreeNode | null): TreeNode[] {
  // One path plus (node, processed) markers: O(h) space.
  const path: TreeNode[] = [];
  const stack: Step[] = [[root, false]];
  while (stack.length > 0) {
    const [node, processed] = stack.pop()!;
    if (processed) {
      path.pop();
      continue;
    }
    if (node === null) continue;
    if (node === target) return [...path, node];
    path.push(node);
    stack.push([node, true]);
    if (node.right !== null) stack.push([node.right, false]);
    if (node.left !== null) stack.push([node.left, false]);
  }
  return [];
}

export function lowestCommonAncestor(
  root: TreeNode | null,
  p: TreeNode | null,
  q: TreeNode | null,
): TreeNode | null {
  if (root === null) return null;
  const pathP = pathTo(root, p);
  const pathQ = pathTo(root, q);
  if (pathP.length === 0 || pathQ.length === 0) {
    if (pathP.length !== 0) return p;
    if (pathQ.length !== 0) return q;
    return null;
  }
  let lca: TreeNode | null = null;
  const n = Math.min(pathP.length, pathQ.length);
  for (let i = 0; i < n; i++) {
    if (pathP[i] !== pathQ[i]) break;
    lca = pathP[i];
  }
  return lca;
}

Template connection

Walk from the root to p and to q with an explicit stack and path markers, then align the two paths from the start. The LCA is the deepest shared node; a missing path means the other node is the answer.

Reflection

  • The two root-to-node paths share a prefix; the last equal node is the LCA.
  • When one node sits under the other, its path contains the other’s path, so the ancestor is the shallower node.
  • If p and q are the same node, that node is the answer. Nodes are compared by identity, not by value.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 5
1/5

LCA of 5 and 1. Search the tree structure: each call returns whether p/q found in a subtree.

351620874

p = 5 · q = 1

Key:CurrentActive rangeMatchSettledEliminated