Number of Good Leaf Nodes Pairs - Problem
You are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance.
Return the number of good leaf node pairs in the tree.
Input & Output
Example 1 — Basic Tree
$
Input:
root = [1,2,3,null,4], distance = 3
›
Output:
1
💡 Note:
The only leaf nodes are 3 and 4. The path between them is 3→1→2→4 with length 3, which equals the distance limit of 3.
Example 2 — Multiple Leaves
$
Input:
root = [1,2,3,4,5,6,7], distance = 3
›
Output:
2
💡 Note:
The leaf nodes are 4,5,6,7. Good pairs are (4,5) with distance 2, and (6,7) with distance 2. Other pairs exceed distance 3.
Example 3 — Single Leaf
$
Input:
root = [1], distance = 1
›
Output:
0
💡 Note:
Only one leaf node exists, so no pairs can be formed.
Constraints
- The number of nodes in the tree is in the range [1, 210].
- 1 ≤ Node.val ≤ 100
- 1 ≤ distance ≤ 10
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Binary tree with leaf nodes and distance limit
2
Find Leaf Pairs
Calculate shortest path between every pair of leaves
3
Count Valid Pairs
Count pairs where path length ≤ distance limit
Key Takeaway
🎯 Key Insight: Use DFS to collect leaf distances and count pairs efficiently in a single tree traversal
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code