Lowest Common Ancestor of a Binary Tree
1 approach, code in every language
Problem description
You are given the root of a binary tree together with two distinct nodes, p and q, that are both guaranteed to appear somewhere in the tree.
The lowest common ancestor (LCA) of p and q is the deepest node in the tree that has both p and q somewhere in its subtree. A node is allowed to be a descendant of itself, so if one of the two nodes sits on the path from the root down to the other, that ancestor node is the answer.
Return the node that is the lowest common ancestor of p and q.
Example 1
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
5 lives in the left subtree of 3 and 1 lives in the right subtree, so the deepest node containing both is the root 3.
Example 2
Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
4 is a descendant of 5 (5 -> 2 -> 4). Because a node counts as its own ancestor, the LCA is 5 itself.
Constraints
The number of nodes in the tree is in the range [2, 10^5].-10^9 <= Node.val <= 10^9All Node.val are unique.p != qBoth p and q exist in the tree.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free