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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code