Lowest Common Ancestor of a Binary Tree II - Problem
Lowest Common Ancestor of a Binary Tree II
You're given a binary tree and two nodes
The LCA is defined as the lowest node in the tree that has both
Key Challenge: Unlike the classic LCA problem, here we must handle the case where one or both nodes don't exist in the tree. If either node is missing, return
Example: In a family tree, if you're looking for the common ancestor of two people, but one person isn't actually part of the family, there's no valid answer!
Goal: Return the LCA if both nodes exist, otherwise return
You're given a binary tree and two nodes
p and q that might or might not exist in the tree. Your task is to find the Lowest Common Ancestor (LCA) of these two nodes.The LCA is defined as the lowest node in the tree that has both
p and q as descendants (where we allow a node to be a descendant of itself).Key Challenge: Unlike the classic LCA problem, here we must handle the case where one or both nodes don't exist in the tree. If either node is missing, return
null.Example: In a family tree, if you're looking for the common ancestor of two people, but one person isn't actually part of the family, there's no valid answer!
Goal: Return the LCA if both nodes exist, otherwise return
null. Input & Output
example_1.py โ Both nodes exist
$
Input:
root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
โบ
Output:
3
๐ก Note:
Both nodes 5 and 1 exist in the tree. Node 3 is their lowest common ancestor since it's the lowest node that has both 5 and 1 as descendants.
example_2.py โ Both nodes exist, one is ancestor
$
Input:
root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
โบ
Output:
5
๐ก Note:
Both nodes exist. Node 4 is a descendant of node 5, so node 5 is the LCA (a node can be an ancestor of itself).
example_3.py โ One node doesn't exist
$
Input:
root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 9
โบ
Output:
null
๐ก Note:
Node 9 doesn't exist in the tree, so there's no valid LCA. We return null as specified.
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
- p and q may or may not exist in the tree
Visualization
Tap to expand
Understanding the Visualization
1
Start at CEO
Begin traversal from the top of the organization
2
Search Departments
Recursively explore each department and team
3
Track Employees
Mark when we find each target employee during our search
4
Identify Manager
The first manager we find who has both employees in their organization (directly or indirectly) is our answer
5
Verify Employment
Only return the manager if we actually found both employees
Key Takeaway
๐ฏ Key Insight: We can efficiently find the LCA and verify node existence in a single traversal by using boolean flags to track our discoveries and post-order traversal to identify the lowest common ancestor.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code