Lowest Common Ancestor of a Binary Tree - Problem

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes p and q in the tree.

According to the definition of LCA: "The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself)."

Note: All node values are unique, and both p and q exist in the tree.

Input & Output

Example 1 — Basic Tree
$ 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 root and both 5 and 1 are in different subtrees.
Example 2 — Ancestor Relationship
$ 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 4 is a descendant of node 5, so 5 is their lowest common ancestor.
Example 3 — Two Node Tree
$ Input: root = [1,2], p = 1, q = 2
Output: 1
💡 Note: In a two-node tree, the root is always the LCA of both nodes.

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
Lowest Common Ancestor Problem351620874Find LCA of nodes 5 and 1Target nodes: 5 (blue) and 1 (blue)Common ancestors: 3Lowest Common Ancestor: 3Algorithm:1. Search for both nodes2. Find deepest common parent3. Return LCA nodeOutput: 3
Understanding the Visualization
1
Input Tree
Binary tree with nodes p and q to find LCA
2
Search Process
Traverse tree to find lowest node containing both targets
3
LCA Found
Return the lowest common ancestor node
Key Takeaway
🎯 Key Insight: The LCA is the deepest node where paths to both targets diverge
Asked in
Facebook 78 Amazon 65 Microsoft 52 Google 48
1.2M Views
High Frequency
~15 min Avg. Time
8.4K 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