AAlgoLoopSpaced repetition for LeetCode
MEDIUMTree / RecursionLeetCode ↗

Lowest Common Ancestor of a Binary Tree

The key idea

Recurse down the tree. A node is the lowest common ancestor when p and q split below it: one target is found in its left subtree and the other in its right subtree. The other case is when the node itself is p or q and the second target lies somewhere beneath it, because a node counts as a descendant of itself.

Problem

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes p and q in the tree. The lowest common ancestor is defined as the lowest node in the tree that has both p and q as descendants, where a node is allowed to be a descendant of itself. Both p and q are guaranteed to exist in the tree, and all node values are unique.

Constraints

Examples

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

Complexity

Time: O(n) Space: O(h)

See the full solution

410310
Step-by-step visualization
Start free →

More Tree / Recursion problems