Tensorum
LeetCode 236 · Lowest Common Ancestor / Distance

Lowest Common Ancestor of a Binary Tree

LeetCode 236 · Medium · solution, intuition & step-by-step walkthrough

left + right + self ≥ 2 ⇒ LCA.

MediumTreeDepth-First SearchBinary TreeBinary LiftingLowest Common Ancestor
63 msruntime · beats 100%
59.2 MBmemory · beats 100%
1approach
8accepted runs · last 14 Dec 2024

This is how I solved Lowest Common Ancestor of a Binary Tree (LeetCode 236), a medium problem from the Lowest Common Ancestor / Distance pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Ask each node: does my subtree contain p or q? A node counts itself (if it's p or q) plus what its left and right subtrees found. The first node where at least two of those three are true is the lowest common ancestor.

Approach

  1. 1

    dfs returns whether p or q is in the subtree.

  2. 2

    left, right from children; mid = node is p or q.

  3. 3

    If left + right + mid ≥ 2, record node.

  4. 4

    Return whether any of them is true.

How I solved it

Post-order countingPythonO(n) time · O(h) space
class Solution:
    def lowestCommonAncestor(self, root, p, q):
        self.ans = None

        def dfs(node):
            if node is None:
                return False
            left = 1 if dfs(node.left) else 0
            right = 1 if dfs(node.right) else 0
            mid = 1 if (node == p or node == q) else 0
            if left + right + mid >= 2:
                self.ans = node
            return left + right + mid > 0
        dfs(root)
        return self.ans
Loading the step-through…

Lowest Common Ancestor of a Binary Tree — FAQ

What is the intuition behind Lowest Common Ancestor of a Binary Tree?

Ask each node: does my subtree contain p or q? A node counts itself (if it's p or q) plus what its left and right subtrees found. The first node where at least two of those three are true is the lowest common ancestor.

How do you solve Lowest Common Ancestor of a Binary Tree (LeetCode 236)?

1. dfs returns whether p or q is in the subtree. 2. left, right from children; mid = node is p or q. 3. If left + right + mid ≥ 2, record node. 4. Return whether any of them is true.

What is the time and space complexity of Lowest Common Ancestor of a Binary Tree?

Time: O(n). Space: O(h). (Accepted approach: Post-order counting.)

What are common mistakes in Lowest Common Ancestor of a Binary Tree?

A node can be its own ancestor (p is the ancestor of q).