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 II INPUT 3 5 p 1 q 6 2 0 8 7 4 root = [3,5,1,6,2,0,8, null,null,7,4] p = 5, q = 1 ALGORITHM STEPS 1 DFS Traversal Recursively search left and right subtrees 2 Check Node Match If node == p or q, mark as found 3 Find LCA Candidate If both left and right return non-null --> LCA 4 Verify Existence Return LCA only if BOTH p and q found DFS Path Visualization 3 5 1 p found: OK q found: OK LCA = 3 FINAL RESULT 3 LCA 5 1 p q Output: 3 Verification: Node 5 exists: OK Node 1 exists: OK LCA(5,1) = 3 Key Insight: Unlike standard LCA, this version requires verifying BOTH nodes exist before returning the answer. Use DFS to find candidates AND track existence. Return null if either p or q is missing from the tree. Time: O(n) | Space: O(h) where h = tree height TutorialsPoint - Lowest Common Ancestor of a Binary Tree II | DFS with Existence Check Approach
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