Lowest Common Ancestor solution explained

The lowest common ancestor of two nodes is the deepest node that has both of them as descendants, where a node counts as its own descendant. In a general binary tree, one recursive pass finds it: each call returns whichever target it found below it, and the first node that hears back from both its left and right side is the answer. In a binary search tree you can skip the recursion and walk down from the root by comparing values.

By Published 8 min read

What is being asked

You get the root of a binary tree and two nodes, p and q, that are both somewhere in it. Return their lowest common ancestor: the node farthest from the root that has both p and q in its subtree. If p is itself an ancestor of q, the answer is p. Interviewers ask this in two flavors, for any binary tree and for a binary search tree, and it helps to ask which one you have before you start.

          1
        /   \
       4     3
      / \   / \
     6   2 9   5
                \
                 7

  p = 6, q = 2  ->  4    (they split at 4)
  p = 6, q = 7  ->  1    (one on each side of the root)
  p = 4, q = 2  ->  4    (4 is an ancestor of 2)
  p = 9, q = 7  ->  3
A tree drawn for this page, with answers from the code below

Clarify three things. Are both nodes guaranteed to be in the tree? The usual version says yes, and the fast solution relies on it. Are you given node references or values? With values and possible duplicates the problem changes. And is the tree a binary search tree? If so, there is a much simpler walk.

Why it is a common question

Lowest common ancestor shows up in real systems, for example finding the nearest shared folder of two files, the closest shared manager of two employees in an org chart, or where two branches of version history diverged. In interviews it tests whether you can design a recursive function whose return value means something specific and then combine the answers from two subtrees. It is a step up from problems like Same Tree, where the return value is only true or false.

A direct approach: compare root-to-node paths

Find the path from the root to p and the path from the root to q. Both start at the root and agree for a while, then split. The last node they share is the answer. Finding each path is a depth-first search, so the time is O(n), but you store two paths of up to O(h) nodes each and walk the tree twice.

def path_to(node, target, path):
    if node is None:
        return False
    path.append(node)
    if node is target or path_to(node.left, target, path) or path_to(node.right, target, path):
        return True
    path.pop()
    return False

def shared_ancestor_by_paths(root, p, q):
    to_p, to_q = [], []
    path_to(root, p, to_p)
    path_to(root, q, to_q)
    last = None
    for a, b in zip(to_p, to_q):
        if a is not b:
            break
        last = a
    return last
Python: build both root-to-node paths and return the last shared node. Nodes have val, left and right.

One pass: let each subtree report back

Define the helper's return value carefully: it returns p or q if it finds one of them in the subtree, the answer if it finds both, and nothing otherwise. A call on an empty spot returns nothing. A call on p or q returns that node at once, without looking further down, because if the other target is below it, this node is the answer anyway. Otherwise the call asks both children. If both report something, p and q are on different sides, so this node is where they split. If only one side reports, pass that report upward.

def shared_ancestor(node, p, q):
    if node is None or node is p or node is q:
        return node
    left = shared_ancestor(node.left, p, q)
    right = shared_ancestor(node.right, p, q)
    if left and right:
        return node  # p and q were found on different sides
    return left or right
Python: single recursive pass. O(n) time, O(h) recursion.
function sharedAncestor(node, p, q) {
  if (node === null || node === p || node === q) return node;
  const left = sharedAncestor(node.left, p, q);
  const right = sharedAncestor(node.right, p, q);
  if (left !== null && right !== null) return node;
  return left !== null ? left : right;
}
JavaScript: the same recursion, comparing node references with ===.

Trace p = 6, q = 7 on the drawing. The left subtree of the root returns 6, since the call on 4 hears 6 from its left and nothing from 2. The right subtree returns 7, passed up through 5 and 3. The root hears from both sides and returns itself, 1. For p = 4 and q = 2, the call on 4 returns immediately with 4, the right side of the root reports nothing, and 4 is the answer.

The binary search tree shortcut

In a binary search tree, every value in a left subtree is smaller than its root and every value on the right is larger. So start at the root. If both targets are smaller, the answer is on the left; if both are larger, it is on the right. The first node where they split, or where one of them sits, is the answer. That only follows one path, O(h) time and O(1) memory.

def shared_ancestor_bst(root, p, q):
    node = root
    while node:
        if p.val < node.val and q.val < node.val:
            node = node.left
        elif p.val > node.val and q.val > node.val:
            node = node.right
        else:
            return node  # the values split here, or one of them is here
    return None
Python: the search tree walk, comparing values instead of searching subtrees.

Complexity

n nodes, height h
ApproachTimeExtra space
Root-to-node paths, comparedO(n)O(h) for each path, plus recursion
Parent map, then climbO(n)O(n) for the map and an ancestor set
One recursive passO(n)O(h) recursion
Search tree walkO(h)O(1)
n nodes, height h. Scroll sideways on a small screen.

Cases to check

  • p and q on opposite sides of the root: the root.
  • p is an ancestor of q: p.
  • p and q are the same node: that node.
  • p and q are siblings: their parent.
  • A chain-shaped tree, where recursion depth equals n.

Pitfalls

  • Using the one-pass recursion when a target might be missing. If only p is in the tree, the function returns p, which looks like a valid answer. Count how many targets were actually found if presence is not guaranteed.
  • Applying the search tree shortcut to an ordinary binary tree, where value comparisons say nothing about position.
  • Comparing nodes by value when duplicates exist. Compare references.
  • Forgetting the case where one node is the ancestor of the other, then descending past it.

Follow-ups

  • Nodes have parent pointers but you do not have the root. Walk up from both nodes; this is the same as finding where two linked lists meet.
  • Many queries on one tree. Precompute depths and binary-lifting tables for O(log n) per query after O(n log n) setup.
  • More than two nodes. Keep the targets in a set. A call returns its node if that node is a target, and the current node when both sides report something, exactly as before.
  • Distance between two nodes. depth(p) + depth(q) minus twice the depth of their lowest common ancestor.

Saying it clearly

Fictional example

One candidate's explanation
Candidate
My helper returns p or q if it finds one of them below, and nothing otherwise. If I land on p or q, I return it right away, because if the other is underneath, this node is the answer anyway.
Candidate
When both children report something, p and q are on different sides, so the current node is where they split. If only one side reports, I pass it up.
Candidate
That's one pass, O(n), and it assumes both nodes exist. If this were a search tree, I'd walk down by comparing values in O(h).

Keep practicing

Validate Binary Search Tree checks the ordering that the shortcut depends on. Binary Tree Right Side View and Same Tree round out this group of tree questions, and the coding problems hub has everything else.

Natively for practice rounds

Practicing on a Mac or Windows computer, you can let Natively read the tree and the two marked nodes from a screenshot, then talk through what the helper's return value means, which is the part most people find hard to state. It keeps a transcript of your mock interview, so you can check whether you mentioned the missing-node assumption. More on the AI assistant for coding interviews.

Questions people ask

How do you find the lowest common ancestor in a binary tree?

Recurse from the root. Return the node if it is p or q, or nothing at an empty spot. If both children return something, the current node is the answer; otherwise pass up whichever side returned a node. It runs in O(n).

How is lowest common ancestor different in a binary search tree?

In a search tree you can compare values. Walk down from the root: go left if both targets are smaller, right if both are larger, and stop at the first node where they split. That is O(h) time and O(1) memory.

Can a node be its own lowest common ancestor?

Yes. A node counts as a descendant of itself, so if p is an ancestor of q, the answer is p.

What if one of the nodes is not in the tree?

The standard one-pass recursion assumes both are present. If that is not guaranteed, count how many targets were found and return nothing unless both were.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP