Dashboard
LC #236

Lowest Common Ancestor of Binary Tree

Pattern · ?MetaAmazonGoogleMicrosoftLinkedIn

Problem

Find the LCA of two nodes p and q in a general binary tree (not necessarily a BST).

Constraints

  • 2 ≤ number of nodes ≤ 10⁵
  • -10⁹ ≤ node.val ≤ 10⁹
  • p and q exist in the tree
  • p ≠ q

Example

Input
root = [3,5,1,6,2,0,8], p = 5, q = 1
Output
3
Why
Node 3 is the deepest ancestor of both 5 and 1

Spot the pattern

Which pattern cracks it?

Hints

One at a time
Solve on LeetCode ↗