Binary Tree Lowest Common Ancestor

Medium · Coding & Algorithms · Machine Learning Engineer · Onsite

Problem Statement

Given the root of an arbitrary binary tree root along with two distinct integer values p and q guaranteed to appear in the tree, return the integer value of their lowest common ancestor (LCA).

All node values in the tree are unique integers, and the tree does not follow binary-search-tree ordering. In standard level-order list inputs, entries appear top-to-bottom and left-to-right with None (null) marking absent child pointers (and omitted descendants below None).

Here, node u is an ancestor of node v whenever u lies along the path from the root down to v—including the case u == v, where u itself is one of the two queried targets. Among all common ancestors of p and q, return the value stored at the deepest one.

Examples

Example 1

  • Input: root = [10, 4, 7, 12, 2, None, 9, None, None, 15, 6], p = 15, q = 9
  • Output: 10
  • Explanation: Node 15 sits along the left branch 10 -> 4 -> 2 -> 15 while node 9 sits along the right branch 10 -> 7 -> 9, so 10 is the deepest node above both.

Example 2

  • Input: root = [10, 4, 7, 12, 2, None, 9, None, None, 15, 6], p = 4, q = 6
  • Output: 4
  • Explanation: Node 6 lies below node 4 (4 -> 2 -> 6), and every node counts as its own ancestor, making 4 the deepest shared ancestor.

Example 3

  • Input: root = [8, -2], p = -2, q = 8
  • Output: 8
  • Explanation: In this two-node tree, -2 is the left child of root 8, so 8 is an ancestor of both -2 and 8.

Constraints

  • The binary tree has between 2 and 100000 nodes inclusive.
  • -1000000000 <= node.val <= 1000000000, and every node has a distinct value.
  • p != q, and both p and q exist in the tree.

Step-by-step walkthrough

  1. Understand the problem and the input format

    In a binary tree, node a is an ancestor of node b whenever a lies along the path from the root down to b — including a == b, since every node is treated as an ancestor of itself. Given two distinct target integers p and q (every node in the tree stores a unique integer), their lowest common ancestor (LCA) is the deepest node that is an ancestor of both p and q.

    Look closely at how lowestCommonAncestorValue(root, p, q) is invoked in the examples: root can be passed as a level-order serialized list such as [10, 4, 7, 12, 2, None, 9, None, None, 15, 6], and the return value is an int (rather than a node object).

    Level-order list: [10, 4, 7, 12, 2, None, 9, None, None, 15, 6]
    
              10            <-- LCA(15, 9) = 10
            /    \
           4      7         <-- LCA(4, 6) = 4 (4 lies above 6 and counts as its own ancestor)
          / \      \
        12   2      9
            / \
           15  6            <-- LCA(15, 6) = 2
    

    Keep in mind that this is an arbitrary binary tree rather than a binary search tree — values are unordered (12 sits to the left of 4!), so comparing p and q numerically against node.val cannot tell us which branch holds them.

  2. Build the `TreeNode` adapter from a level-order list

    In standard level-order list format, raw_root[0] is the root, followed by the left and right children of each non-null node from top to bottom, left to right (None entries have no children listed after them).

    We reconstruct TreeNode objects using a first-in-first-out (FIFO) queue (collections.deque, which pops from the front in O(1) time):

    1. Create root = TreeNode(raw_root[0]) and push it into queue, starting idx = 1.
    2. Pop parent from the front of queue. Read raw_root[idx] for parent.left (checking is not None explicitly because 0 is a valid node value!), advance idx, and do the same for parent.right.
    3. Check isinstance(raw_root, (list, tuple)) first so if a caller passes a pre-built node object directly, we return it unchanged.
    from collections import deque
    from typing import Any, Optional
    
    
    class TreeNode:
        """Binary tree node constructed from the serialized level-order input list."""
    
        def __init__(
            self,
            val: int,
            left: Optional["TreeNode"] = None,
            right: Optional["TreeNode"] = None,
        ) -> None:
            self.val = val
            self.left = left
            self.right = right
    
    
    def _build_tree(raw_root: Any) -> Optional[TreeNode]:
        """Convert a level-order list like [10, 4, 7, None, 9] (or an existing node) into a TreeNode root."""
        if raw_root is None:
            return None
        # Support callers that pass an already-constructed node object directly.
        if not isinstance(raw_root, (list, tuple)):
            return raw_root
        if not raw_root or raw_root[0] is None:
            return None
    
        root = TreeNode(raw_root[0])
        # queue: FIFO queue of non-null parent TreeNodes waiting to receive left and right children.
        queue: deque[TreeNode] = deque([root])
        idx = 1
        total = len(raw_root)
    
        while queue and idx < total:
            parent = queue.popleft()
    
            # Check `is not None` explicitly because 0 is a valid node value.
            if idx < total and raw_root[idx] is not None:
                parent.left = TreeNode(raw_root[idx])
                queue.append(parent.left)
            idx += 1
    
            if idx < total and raw_root[idx] is not None:
                parent.right = TreeNode(raw_root[idx])
                queue.append(parent.right)
            idx += 1
    
        return root
    
  3. Why iterative integer parent links beat naive recursion

    Look at two key constraints in the problem statement:

    • The tree can contain up to 100,000 nodes. If all 100,000 nodes form a skewed chain (0 -> 1 -> 2 -> ... -> 99999), Python's default recursion limit (1,000 stack frames) will crash any plain recursive traversal with RecursionError.
    • Every node value is a distinct integer. That lets us store parent links in a simple integer dictionary parent_of: Dict[int, Optional[int]] ({10: None, 4: 10, 7: 10, ...}) instead of hashing node objects!

    Using an explicit stack list to populate parent_of gives us zero recursion-depth risk, works even if a caller passes unhashable @dataclass nodes, and makes every ancestor step easy to trace by value.

  4. Record parent values until both `p` and `q` are found

    Start stack = [tree_root] and parent_of = {tree_root.val: None}. In each step of iterative depth-first search (DFS) (exploring branches via an explicit stack):

    • Pop node and mark found_p = True if node.val == p (or found_q = True if node.val == q).
    • For each non-null child (node.left, node.right), record parent_of[child.val] = node.val and push child onto stack.
    • Stop as soon as both found_p and found_q are True — once both targets have been visited, their entire ancestor chains back to the root are already in parent_of!
    parent_of: Dict[int, Optional[int]] = {tree_root.val: None}
    stack: List[Any] = [tree_root]
    
    found_p = False
    found_q = False
    
    while stack and not (found_p and found_q):
        node = stack.pop()
        if node.val == p:
            found_p = True
        if node.val == q:
            found_q = True
    
        if node.left is not None:
            parent_of[node.left.val] = node.val
            stack.append(node.left)
        if node.right is not None:
            parent_of[node.right.val] = node.val
            stack.append(node.right)
    
  5. Intersect the two upward ancestor chains

    Now two short while loops find the LCA:

    1. Collect p's ancestors: Start curr = p and follow curr = parent_of[curr] up to None, adding every integer visited (including p itself!) to a hash set ancestors_of_p. Always write while curr is not None: (never while curr:), because 0 is a valid node value!
    2. Climb from q until hitting the set: Start curr_q = q and step upward curr_q = parent_of[curr_q] while curr_q not in ancestors_of_p. Because q's path walks strictly from deepest to shallowest and tree_root.val is in ancestors_of_p, the first value in ancestors_of_p that curr_q reaches is the lowest common ancestor.
    Trace on Example 1 (p = 15, q = 9) and Example 2 (p = 4, q = 6):
      parent_of = {10: None, 4: 10, 7: 10, 12: 4, 2: 4, 9: 7, 15: 2, 6: 2}
    
    Example 1 (p = 15, q = 9):
      ancestors_of_p (from 15 up): {15, 2, 4, 10}
      climb from q = 9:
        curr_q = 9  -> in {15, 2, 4, 10}? No  -> parent_of[9] = 7
        curr_q = 7  -> in {15, 2, 4, 10}? No  -> parent_of[7] = 10
        curr_q = 10 -> in {15, 2, 4, 10}? Yes -> return 10
    
    Example 2 (p = 4, q = 6):
      ancestors_of_p (from 4 up): {4, 10}
      climb from q = 6:
        curr_q = 6 -> in {4, 10}? No  -> parent_of[6] = 2
        curr_q = 2 -> in {4, 10}? No  -> parent_of[2] = 4
        curr_q = 4 -> in {4, 10}? Yes -> return 4
    
  6. Complete solution

    from collections import deque
    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class TreeNode:
        """Binary tree node constructed from the serialized level-order input list."""
    
        def __init__(
            self,
            val: int,
            left: Optional["TreeNode"] = None,
            right: Optional["TreeNode"] = None,
        ) -> None:
            self.val = val
            self.left = left
            self.right = right
    
    
    def _build_tree(raw_root: Any) -> Optional[TreeNode]:
        """Convert a level-order list like [10, 4, 7, None, 9] (or an existing node) into a TreeNode root."""
        if raw_root is None:
            return None
        # Support callers that pass an already-constructed node object directly.
        if not isinstance(raw_root, (list, tuple)):
            return raw_root
        if not raw_root or raw_root[0] is None:
            return None
    
        root = TreeNode(raw_root[0])
        # queue: FIFO queue of non-null parent TreeNodes waiting to receive left and right children.
        queue: deque[TreeNode] = deque([root])
        idx = 1
        total = len(raw_root)
    
        while queue and idx < total:
            parent = queue.popleft()
    
            # Check `is not None` explicitly because 0 is a valid node value.
            if idx < total and raw_root[idx] is not None:
                parent.left = TreeNode(raw_root[idx])
                queue.append(parent.left)
            idx += 1
    
            if idx < total and raw_root[idx] is not None:
                parent.right = TreeNode(raw_root[idx])
                queue.append(parent.right)
            idx += 1
    
        return root
    
    
    def lowestCommonAncestorValue(root: Any, p: int, q: int) -> int:
        tree_root = _build_tree(root)
        if tree_root is None:
            raise ValueError("Tree must contain at least two nodes.")
    
        # Because all node values are unique ints, map child_val -> parent_val (None for the root),
        # e.g. {10: None, 4: 10, 7: 10}. Keying by int works even if input nodes are unhashable dataclasses.
        parent_of: Dict[int, Optional[int]] = {tree_root.val: None}
        # stack: explicit DFS stack of node pointers so 100,000-node chains never hit RecursionError.
        stack: List[Any] = [tree_root]
    
        found_p = False
        found_q = False
    
        # Phase 1: Traverse the tree until both target values p and q have been located.
        while stack and not (found_p and found_q):
            node = stack.pop()
            if node.val == p:
                found_p = True
            if node.val == q:
                found_q = True
    
            if node.left is not None:
                parent_of[node.left.val] = node.val
                stack.append(node.left)
            if node.right is not None:
                parent_of[node.right.val] = node.val
                stack.append(node.right)
    
        # Phase 2: Climb from p up to the root, recording p and every ancestor value above p.
        # Use `curr is not None` (never `while curr:`) so node value 0 is not treated as None!
        ancestors_of_p: Set[int] = set()
        curr: Optional[int] = p
        while curr is not None:
            ancestors_of_p.add(curr)
            curr = parent_of[curr]
    
        # Phase 3: Climb upward from q; the first value in ancestors_of_p is the lowest common ancestor.
        curr_q: Optional[int] = q
        while curr_q is not None and curr_q not in ancestors_of_p:
            curr_q = parent_of[curr_q]
    
        assert curr_q is not None
        return curr_q
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of a binary tree like a family lineage chart descending from one founder at the top: to locate the lowest common ancestor (LCA) (the deepest node in the tree whose subtree holds both p and q, treating every node as its own ancestor), imagine highlighting p and every ancestor straight up to the founder, then starting at q and walking upward one generation at a time. The very first highlighted ancestor you step onto is guaranteed to be the deepest ancestor shared by both targets.

Why do simpler shortcuts fail here? First, this is an arbitrary binary tree rather than a binary search tree (BST) (a tree where left descendants are smaller and right descendants are larger), so comparing p and q against node.val tells us nothing about which branch holds them. Second, checking "does this node's subtree contain both p and q?" from scratch at every node along the path wastes O(N^2) time on skewed trees, and plain Python recursion crashes with RecursionError when 100,000 nodes form a single chain deeper than Python's 1,000-frame call-stack limit.

Because the judge can pass root as a level-order serialized list (a flat list listing nodes top-to-bottom and left-to-right, omitting children of None entries), we first run deserialization (reconstructing TreeNode objects with .left and .right pointers using a queue), then run iterative depth-first search (DFS) (exploring nodes with an explicit stack list) to record parent_of[child.val] = node.val using each node's unique integer value: - On Example 2 ([10, 4, 7, 12, 2, None, 9, None, None, 15, 6], p = 4, q = 6), _build_tree links 10 -> (4, 7), 4 -> (12, 2), 7 -> (None, 9), and 2 -> (15, 6). - The DFS stack records integer parent links (parent_of[4] = 10, parent_of[2] = 4, parent_of[6] = 2, ...) and stops once both 4 and 6 are located. - Walking upward from 4 puts {4, 10} into ancestors_of_p; walking upward from 6 visits 6 -> 2 -> 4, hits 4 in {4, 10}, and returns 4.

Complexity

Let N be the number of nodes in the binary tree (L entries in the input list, where L <= 2N + 1).

  • Time: O(N). Deserializing the level-order list pops each of the N nodes from the deque once (O(N)). Iterative DFS pushes and pops each node at most once with O(1) dictionary insertions (O(N)), and the two upward climbs from p and q each take at most N steps with O(1) average hash-set lookups (O(N)).
  • Space: O(N). The constructed TreeNode objects, the parent_of dictionary, the DFS stack, and ancestors_of_p each store at most N entries (O(N) total memory).

Edge cases

  • One target is an ancestor of the other (p = 4, q = 6 or p = 6, q = 4): Because ancestors_of_p starts by adding p itself (and curr_q checks membership before stepping to parent_of[curr_q]), both orderings return 4.
  • Two-node tree (root = [8, -2], p = -2, q = 8): tree_root itself is one of the targets, and ancestors_of_p = {-2, 8} matches immediately when curr_q starts at 8.
  • Deep skewed chain (N = 100,000 nodes in a single line): Both _build_tree (using deque) and the DFS traversal (using stack) are iterative, so Python's recursion limit is never touched.
  • Sparse level-order lists with None branches ([10, 20, None, None, 30, 40, 50]): Using a queue during _build_tree rather than heap-index formulas (2 * i + 1, 2 * i + 2) attaches 40 and 50 under 30 even though 10's right child was None.
  • Zero and negative boundary values (-10^9, 0, 10^9): Checking is not None explicitly both in _build_tree and in while curr is not None: ensures node value 0 is never mistaken for None.
  • Unhashable pre-built node objects (such as @dataclass nodes): Keying parent_of and ancestors_of_p by integer .val rather than node instances avoids TypeError: unhashable type.

Common mistakes

  • Treating the input list as a complete binary heap (left = 2*i + 1, right = 2*i + 2): Standard tree serialization omits children of None nodes; 2*i + 1 indexing misplaces every node below the first None gap and goes out of bounds on skewed trees.
  • Writing if raw_root[idx]: or while curr: instead of is not None: In Python, 0 is falsy! Truthiness checks silently drop any node whose value is 0 or abort the ancestor climb early at 0.
  • Forgetting to include p in ancestors_of_p (or stepping curr_q before checking): Excluding p or q from its own ancestor chain returns the strict parent above p instead of p when q lies inside p's subtree.
  • Using unguarded recursion on N <= 100,000: Recursive tree traversal hits RecursionError whenever tree height exceeds ~1,000.

Alternative approaches

  • Bottom-up postorder DFS (O(N) time, O(H) stack space on pointer trees): In a postorder traversal (visiting both left and right children before combining results at the parent), each subtree returns node if node.val in (p, q), bubbles up a single non-null child answer, or returns node as the LCA when both left and right subtrees return non-null. Simulated iteratively with (node, visited_children) stack frames, this avoids building parent_of and uses O(H) auxiliary space, where H is the tree height.

Follow-up questions

  • How would you adapt the algorithm if one or both target values might be absent from the tree and you should return None in that case? With our iterative parent-map search, you only add one check right after Phase 1: if not (found_p and found_q): return None! By contrast, classic single-pass recursive postorder returns p immediately upon seeing p without exploring p's subtree, so it would falsely return p even when q is absent unless modified to search the whole tree and count how many targets were found.
  • If nodes already store parent pointers and you receive direct references to both target nodes, how can you find their lowest common ancestor in O(1) auxiliary space? Use the two-runner intersection trick: set a = node_p and b = node_q, and at each step advance a = a.parent if a is not None else node_q and b = b.parent if b is not None else node_p until a is b. If p has depth d_p and q has depth d_q, both runners walk the exact same total distance d_p + d_q - d_lca before meeting at the LCA in O(H) time and O(1) memory.
  • How would you preprocess a static 100,000-node tree to answer 100,000 lowest-common-ancestor queries quickly? Preprocess the tree once in O(N log N) time and space using binary lifting (precomputing up[node][k], the 2^k-th ancestor of node for k = 0 .. 17, alongside each node's depth), so each query equalizes depths and jumps upward in powers of two in O(log N) time; alternatively, reducing LCA to Range Minimum Query (RMQ) (finding the minimum element in an array subarray) over an Euler tour (the array of node depths recorded while walking around the tree) answers each query in O(1) time after O(N log N) table setup.

Follow-up questions

Similar questions

More Meta interview questions

All 787 Meta questions →