Lowest Common Ancestor of a Binary Tree - Problem
Given a binary tree and two nodes p and q, find their Lowest Common Ancestor (LCA). The LCA is defined as the deepest node that has both p and q as descendants (a node can be a descendant of itself).

Think of it like a family tree - if you have two people, their lowest common ancestor is their most recent shared relative. In a binary tree, it's the node closest to the leaves that can reach both target nodes by going down the tree.

Goal: Return the LCA node of the two given nodes.
Input: Root of binary tree and two target nodes p and q
Output: The LCA node

Input & Output

example_1.py โ€” Basic LCA
$ Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
โ€บ Output: 3
๐Ÿ’ก Note: The LCA of nodes 5 and 1 is 3. Node 3 is the lowest node that has both 5 and 1 as descendants.
example_2.py โ€” LCA is one of the nodes
$ Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
โ€บ Output: 5
๐Ÿ’ก Note: The LCA of nodes 5 and 4 is 5. Node 5 is an ancestor of node 4, so it serves as the LCA.
example_3.py โ€” Simple two-node tree
$ Input: root = [1,2], p = 1, q = 2
โ€บ Output: 1
๐Ÿ’ก Note: In a simple tree with root 1 and left child 2, the LCA of 1 and 2 is 1 (the root).

Constraints

  • The number of nodes in the tree is in the range [2, 105]
  • -109 โ‰ค Node.val โ‰ค 109
  • All Node.val are unique
  • p โ‰  q
  • p and q will exist in the tree

Visualization

Tap to expand
Family Tree LCA Detective WorkGreat GrandpaGrandpa AGrandpa BDad 1Dad 2Dad 3Child PCousinChild QTarget P: Child P (left branch)Target Q: Child Q (right branch)LCA: Great Grandpa (convergence point!)Detective Process:1. Search left: Found Child P โœ“2. Search right: Found Child Q โœ“3. Both found โ†’ Great Grandpa is LCA!
Understanding the Visualization
1
Start the search
Begin from the family tree root and explore downward
2
Locate descendants
Find which branches contain each target person
3
Find convergence
The first ancestor who has both people in different branches is the LCA
Key Takeaway
๐ŸŽฏ Key Insight: The LCA is the deepest node that sits at the "fork in the road" between two target nodes - where their paths through the tree diverge.
Asked in
Meta 85 Amazon 72 Google 68 Microsoft 45 Apple 32
142.4K Views
Very High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen