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).

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.
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

Recursive DFS

The key observations:

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):