Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the Lowest Common Ancestor (LCA) of two given nodes p and q.

The LCA is defined as the deepest node that has both p and q as descendants (a node can be a descendant of itself).

Example 1
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: LCA of nodes 5 and 1 is 3.
Example 2
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself.
Constraints:

Contents

Solution: Recursive DFS

The key observations:

Java
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if (root == null) return null;

    // If root is p or q, it is the LCA (or will propagate up)
    if (root == p || root == q) return root;

    TreeNode left  = lowestCommonAncestor(root.left,  p, q);
    TreeNode right = lowestCommonAncestor(root.right, p, q);

    // p found in one subtree, q in the other — current node is LCA
    if (left != null && right != null) return root;

    // Both in same subtree — propagate the found node up
    return left != null ? left : right;
}
Trace for Example 1 (p=5, q=1):

Complexity Analysis