Imagine you're working with a family tree represented as a binary tree, where each person has a unique identifier. Your task is to find the shortest path between any two family members in the tree.
Given the root of a binary tree and two integers p and q representing two nodes in the tree, return the distance between the nodes with values p and q.
The distance is defined as the number of edges on the shortest path connecting the two nodes. This path always goes through their Lowest Common Ancestor (LCA) - think of it as the closest common relative that connects both family members.
Key insight: The distance between two nodes equals the sum of their depths from their LCA: distance = depth(p from LCA) + depth(q from LCA)
Input & Output
Constraints
- The number of nodes in the tree is in the range [2, 104]
- 1 โค Node.val โค 104
- All node values are unique
- p โ q
- Both p and q exist in the tree