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 of a Binary Tree INPUT 3 5 (p) 1 (q) 6 2 0 8 7 4 p = 5, q = 1 Find LCA of nodes p and q ALGORITHM STEPS (Recursive DFS) 1 Base Case Check If node is null, p, or q return the node 2 Recurse Left/Right Search both subtrees for p and q 3 Check Results If both sides found: current node is LCA 4 Return Result Return non-null side or null if neither DFS at Node 3: left(5) found p right(1) found q Both non-null --> LCA = 3 FINAL RESULT 3 LCA 5 1 6 2 0 8 Output: 3 Node 3 is ancestor of both 5 and 1 - OK Key Insight: The LCA is the node where one target is found in the left subtree and the other in the right subtree. If both p and q are in one subtree, the LCA is in that subtree. The recursion naturally finds this split point. Time: O(n) | Space: O(h) where h is tree height TutorialsPoint - Lowest Common Ancestor of a Binary Tree | Recursive DFS Approach
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