SDE & MLE Prep

236. Lowest Common Ancestor of a Binary Tree

Problem

Given a binary tree (not a BST) and two of its nodes p and q, return their lowest common ancestor: the deepest node that has both as descendants (a node counts as its own descendant).

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

Constraints: up to 10⁵ nodes; values are unique.

DFS returns p or q if found in the subtree (else null). If both sides return non-null, the current node is the LCA; otherwise bubble up whichever side is non-null.

Complexity: O(n).

class Solution:
    def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
        if not root or root is p or root is q:
            return root
        l = self.lowestCommonAncestor(root.left, p, q)
        r = self.lowestCommonAncestor(root.right, p, q)
        return root if l and r else l or r