Find Distance in a Binary Tree - Problem
Given the root of a binary tree and two integers p and q, return the distance between the nodes of value p and q in the tree.
The distance between two nodes is the number of edges on the path from one to the other.
Note: You can assume that both values p and q exist in the tree and all node values are unique.
Input & Output
Example 1 — Basic Distance
$
Input:
root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
›
Output:
3
💡 Note:
The path from node 5 to node 1 is: 5 → 3 → 1, which has 2 edges. So the distance is 2.
Example 2 — Same Subtree
$
Input:
root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
›
Output:
3
💡 Note:
The path from node 5 to node 4 is: 5 → 2 → 4, which has 2 edges. So the distance is 2.
Example 3 — Adjacent Nodes
$
Input:
root = [1,2,3], p = 2, q = 3
›
Output:
2
💡 Note:
The path from node 2 to node 3 is: 2 → 1 → 3, which has 2 edges. So the distance is 2.
Constraints
- The number of nodes in the tree is in the range [1, 104]
- 0 ≤ Node.val ≤ 104
- All Node.val are unique
- p ≠ q
- p and q exist in the tree
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Binary tree with two target nodes p and q
2
Find LCA
Locate the lowest common ancestor of both nodes
3
Calculate Distance
Sum distances from LCA to each target node
Key Takeaway
🎯 Key Insight: The shortest path between any two nodes always goes through their lowest common ancestor
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code