MediumTreeDepth-First SearchBinary Tree

Lowest Common Ancestor of a Binary Tree

LeetCode
1 approach, code in all languages

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^9
  • All Node.val are unique.
  • p != q
  • Both p and q exist in the tree.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now