Lowest Common Ancestor of a Binary Tree II - Problem

Given the root of a binary tree, return the lowest common ancestor (LCA) of two given nodes, p and q. If either node p or q does not exist in the tree, return null.

All values of the nodes in the tree are unique. According to the definition of LCA on Wikipedia: "The lowest common ancestor of two nodes p and q in a binary tree T is the lowest node that has both p and q as descendants (where we allow a node to be a descendant of itself)."

A descendant of a node x is a node y that is on the path from node x to some leaf node.

Input & Output

Example 1 — Both Nodes Exist
$ 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 node 3. Node 5 is in the left subtree of 3, and node 1 is in the right subtree of 3.
Example 2 — One Node is Ancestor
$ 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 node 5, since a node can be a descendant of itself. Node 4 is in the subtree of node 5.
Example 3 — Node Doesn't Exist
$ Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 10
Output: null
💡 Note: Node 10 does not exist in the tree, so we return null instead of finding an LCA.

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • -109 ≤ Node.val ≤ 109
  • All Node.val are unique
  • p ≠ q

Visualization

Tap to expand
Lowest Common Ancestor of Binary Tree IIInput: Find LCA of p=5, q=135162Process: Check existence + Find LCABoth nodes exist ✓p=5 in left subtreeq=1 in right subtreeOutput3LCA Found!Key difference from LCA I: We return null if either node doesn't exist
Understanding the Visualization
1
Input Tree
Binary tree with nodes p=5 and q=1 to find LCA
2
Verify Existence
Confirm both target nodes exist in the tree
3
Find LCA
Return lowest node that has both as descendants
Key Takeaway
🎯 Key Insight: Must verify both nodes exist in the tree before finding their lowest common ancestor
Asked in
Facebook 35 Microsoft 28 Amazon 22 Google 18
23.4K Views
Medium-High Frequency
~18 min Avg. Time
892 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