Lowest Common Ancestor of a Binary Tree II

Medium

Topics
Hash TableTreeDFSBinary Tree

Given the root of a binary tree with distinct node values, and two values p and q, return the value of their lowest common ancestor.

The lowest common ancestor of p and q is the deepest node that has both of them as descendants, where a node counts as a descendant of itself.

Unlike the classic version of this problem, p or q may be absent from the tree. If either one is missing, return -1.

Example 1

65p7243answer01q8
the two values being looked upthe answer
The two marked values sit in different subtrees of 3, and no node below it holds both, so the answer is 3.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The two values sit in different subtrees of the root, so the root is the lowest node containing both.

Example 2

65p = answer724q3018
the two values being looked up
A node counts as its own descendant, so when one value sits below the other the higher one is the answer. Here 5 contains both, and nothing deeper does, giving 5.
Input:  root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: Node 4 is a descendant of 5, and a node is its own descendant, so 5 is the answer.

Example 3

65p7243018
the two values being looked up
A common ancestor has to contain both values below it, and 10 is nowhere in this tree. Finding 5 is not enough on its own — so there is no answer and the result is -1. This is the whole difference from the classic version, where both values are promised to exist.
Input:  root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 10
Output: -1
Explanation: There is no node with value 10, so no common ancestor exists.

Constraints

  • 1 <= number of nodes <= 10^4
  • -10^9 <= Node.val <= 10^9
  • All Node.val are unique
  • p != q
Editorial — intuition, approach, complexity and pitfalls

Intuition

The classic version is allowed to stop the moment it finds either target, because both are guaranteed present. Here that shortcut is exactly what breaks: if q is missing, finding p and returning it reports p as the answer, which is wrong — there is no answer at all.

So presence has to be established before any ancestor is reported. The cheap way to do that is to make the traversal count what it finds rather than stop at the first hit: visit the whole tree, and have each node report back both the candidate ancestor beneath it and how many of the two targets live down there.

A node is the lowest common ancestor exactly when the subtree rooted at it contains both targets and no child’s subtree does. Tracking the count gives that test directly, and it also answers the absence question for free — if the count at the root is less than two, one of the targets is not in the tree.

Approach

  1. Recurse over every node, returning two things: the best candidate found in this subtree, and how many of {p, q} it contains.
  2. At a node, recurse into both children first, then add one if the node’s own value is p or q.
  3. If the total count for this node’s subtree is 2 and neither child already reported a candidate, this node is the lowest common ancestor — report it.
  4. Otherwise pass up whichever child’s candidate exists, along with the count.
  5. At the top, return the candidate only if the root’s count reached 2; otherwise return -1.

Walkthrough

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

            3
          /   \
         5     1
        / \   / \
       6   2 0   8
          / \
         7   4

subtree rooted at   contains p,q   candidate
  6                      0           -
  7                      0           -
  4                      1 (q)        -
  2                      1            -
  5                      2 (p and q)  5   <- both found, no child had a candidate
  1                      0            -
  3                      2            5   (passed up unchanged)

root count is 2, so the answer is 5

With q = 10 instead, the root count is 1 and the answer is -1,
even though node 5 was found along the way.

Complexity

  • Time — O(n): every node is visited exactly once. The whole tree must be visited, since stopping early is what makes the absent case unanswerable.
  • Space — O(h): the recursion stack, where h is the tree height.

Common Pitfalls

  • Reusing the classic solution unchanged. It returns a node whenever it finds one target, so a missing q yields p instead of -1.
  • Checking presence with two separate searches and then running the classic version. That works but walks the tree three times; one counting pass does the same job.
  • Forgetting that a node is its own descendant. Example 2 answers 5, not 2, because the ancestor relation includes the node itself.
  • Reporting the first node whose count reaches 2 while unwinding without checking the children. The deepest such node is wanted, so a child’s candidate always wins.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def lowestCommonAncestor(self, root, p, q):
        def walk(node):
            if not node:
                return None, 0
            left, left_n = walk(node.left)
            right, right_n = walk(node.right)
            found = left_n + right_n + (1 if node.val in (p, q) else 0)
            if left:
                return left, found
            if right:
                return right, found
            if found == 2:
                return node, found
            return None, found

        node, found = walk(root)
        return node.val if found == 2 and node else -1
SensAI
Beta
Tap the mic to stop voice mode