Browse curriculum

Lowest Common Ancestor of a Binary Tree (LeetCode 236)

Lowest Common Ancestor of a Binary Tree (LeetCode 236): find the deepest node that has both p and q as descendants with one depth-first pass.

Problem Understanding

Lowest Common Ancestor of a Binary Tree: given the root of a binary tree and two of its nodes p and q, return their lowest common ancestor: the deepest node that has both p and q as descendants. A node counts as a descendant of itself, and both nodes are guaranteed to exist.

Example: in [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], the LCA of 5 and 1 is 3; the LCA of 5 and 4 is 5.

Attempt 1: Record Both Paths

Find the path from the root to p and the path to q (two depth-first searches), then walk both paths together; the last node they share is the LCA. It is correct and O(n), but it needs two searches and O(h) extra lists. One pass can do it if each subtree simply reports what it found.

The Intuition: Let Each Subtree Report Back

Ask every subtree one question: did you find p or q? Each call returns:

  1. null for an empty subtree.
  2. The node itself if it is p or q: there is no need to search below it.
  3. Otherwise, the answers from both children combined: if both sides found something, p and q are split across this node, so it is the LCA. If only one side found something, pass that up unchanged.

The first node to hear from both sides is the lowest one, because every call below it heard from at most one side.

Lowest Common Ancestor of a Binary Tree Visualization

p = 5, q = 1 · → X = WHAT A CALL RETURNED

CALL

Stack depth

1

LCA

:

call stack

lca(3)

 

lca(3)

Next

Search 3's left subtree

Free preview: the first 3 of 9 steps

Tree

p, q

p and q are labelled in the tree. The calls in progress are outlined from the root down to the running one, and each call's report appears under its node when it returns, so you can watch the answers flow up until one node hears from both sides.

Lowest Common Ancestor of a Binary Tree Dry Run

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

Call What happens Returns
lca(3) not p or q; ask the left child -
lca(5) is p: stop, nothing below is searched 5
lca(3) left reported 5; ask the right child -
lca(1) is q 1
lca(3) left 5, right 1: both sides found something 3

The LCA is 3. With q = 4 instead, lca(1) would return null and 3 would pass 5 up: the LCA would be 5.

Lowest Common Ancestor of a Binary Tree LeetCode Solution

Post-order DFS: combine what the two subtrees report.

Lowest Common Ancestor of a Binary Tree Code
1var lowestCommonAncestor = function(root, p, q) {
2 if (root === null || root === p || root === q) {
3 return root;
4 }
5 const left = lowestCommonAncestor(root.left, p, q);
6 const right = lowestCommonAncestor(root.right, p, q);
7 if (left && right) {
8 return root;
9 }
10 return left ?? right;
11};

Lowest Common Ancestor of a Binary Tree in Python, Java, C++, TypeScript and C

Lowest Common Ancestor of a Binary Tree in Python
class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if root is None or root is p or root is q:
            return root
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)
        if left and right:
            return root
        return left if left else right
Lowest Common Ancestor of a Binary Tree in Java
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) {
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left != null && right != null) {
            return root;
        }
        return left != null ? left : right;
    }
}
Lowest Common Ancestor of a Binary Tree in C++
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if (!root || root == p || root == q) {
            return root;
        }
        TreeNode* left = lowestCommonAncestor(root->left, p, q);
        TreeNode* right = lowestCommonAncestor(root->right, p, q);
        if (left && right) {
            return root;
        }
        return left ? left : right;
    }
};
Lowest Common Ancestor of a Binary Tree in TypeScript
function lowestCommonAncestor(root: TreeNode | null, p: TreeNode | null, q: TreeNode | null): TreeNode | null {
    if (root === null || root === p || root === q) {
        return root;
    }
    const left = lowestCommonAncestor(root.left, p, q);
    const right = lowestCommonAncestor(root.right, p, q);
    if (left && right) {
        return root;
    }
    return left ?? right;
}
Lowest Common Ancestor of a Binary Tree in C
struct TreeNode* lowestCommonAncestor(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
    if (root == NULL || root == p || root == q) {
        return root;
    }
    struct TreeNode *left = lowestCommonAncestor(root->left, p, q);
    struct TreeNode *right = lowestCommonAncestor(root->right, p, q);
    if (left && right) {
        return root;
    }
    return left ? left : right;
}

Edge Cases & Common Mistakes

  • One target is an ancestor of the other: the call reaching it returns at once, and nothing higher hears from a second side, the ancestor itself is the answer.
  • p or q is the root: the first call returns the root.
  • Comparing values instead of nodes: the problem passes nodes; with duplicate values, comparing val can stop at the wrong node.
  • Assuming both nodes exist: this method relies on the guarantee. If a target might be missing, it can return the other target as a false answer; a variant must count how many targets were actually found.

Summary

Let each subtree report whether it found p or q; the lowest node hearing from both sides is the LCA. One post-order pass: O(n) time, O(h) stack space.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Base cases

    Return null for an empty subtree, and return the node itself when it is p or q.

  2. Ask both children

    Recurse into the left and right subtrees.

  3. Combine

    If both children returned a node, return the current node; otherwise return whichever result is not null.

Frequently asked questions

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

Recurse from the root. A call returns null for an empty subtree and returns the node itself if it is p or q. Otherwise it asks both children: if both return something, this node is the LCA; if only one does, that result is passed up.


Why can the search stop when it reaches p or q?

If the other target is below that node, the node is the answer anyway, since a node counts as its own ancestor. If the other target is elsewhere, a higher node will hear from both sides and return itself instead.


How is this different from the LCA of a binary search tree?

In a BST, values tell you which way to go: walk down from the root until p and q fall on different sides, in O(h) time without exploring both subtrees. A general binary tree has no ordering, so both subtrees must be searched: O(n) time.

New to the technique behind this problem? Watch it run step by step:

Depth First Search Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description