Lowest Common Ancestor of a Binary Tree - Problem
Given a binary tree and two nodes
Think of it like a family tree - if you have two people, their lowest common ancestor is their most recent shared relative. In a binary tree, it's the node closest to the leaves that can reach both target nodes by going down the tree.
Goal: Return the LCA node of the two given nodes.
Input: Root of binary tree and two target nodes p and q
Output: The LCA node
p and q, find their Lowest Common Ancestor (LCA). The LCA is defined as the deepest node that has both p and q as descendants (a node can be a descendant of itself).Think of it like a family tree - if you have two people, their lowest common ancestor is their most recent shared relative. In a binary tree, it's the node closest to the leaves that can reach both target nodes by going down the tree.
Goal: Return the LCA node of the two given nodes.
Input: Root of binary tree and two target nodes p and q
Output: The LCA node
Input & Output
example_1.py โ Basic LCA
$
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 lowest node that has both 5 and 1 as descendants.
example_2.py โ LCA is one of the nodes
$
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 5 is an ancestor of node 4, so it serves as the LCA.
example_3.py โ Simple two-node tree
$
Input:
root = [1,2], p = 1, q = 2
โบ
Output:
1
๐ก Note:
In a simple tree with root 1 and left child 2, the LCA of 1 and 2 is 1 (the root).
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
Understanding the Visualization
1
Start the search
Begin from the family tree root and explore downward
2
Locate descendants
Find which branches contain each target person
3
Find convergence
The first ancestor who has both people in different branches is the LCA
Key Takeaway
๐ฏ Key Insight: The LCA is the deepest node that sits at the "fork in the road" between two target nodes - where their paths through the tree diverge.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code