Number of Good Leaf Nodes Pairs - Problem
Given the root of a binary tree and an integer distance, you need to find all "good" leaf node pairs.
A pair of two different leaf nodes is considered good if the shortest path between them has length less than or equal to distance. The shortest path between two nodes is measured by counting the number of edges in the path.
Goal: Return the total number of good leaf node pairs in the tree.
Example: If we have leaf nodes A and B, and the path from A to their lowest common ancestor to B has 3 edges total, then this pair is good if distance >= 3.
Input & Output
example_1.py โ Basic Tree
$
Input:
root = [1,2,3,null,4], distance = 3
โบ
Output:
1
๐ก Note:
The only leaf nodes are 4 and 3. The distance between them is 3 (4โ2โ1โ3), which equals our distance limit, so this pair counts.
example_2.py โ Multiple Leaves
$
Input:
root = [1,2,3,4,5,6,7], distance = 3
โบ
Output:
2
๐ก Note:
The leaf nodes are [4,5,6,7]. Valid pairs are (4,5) with distance 2, and (6,7) with distance 2. Other pairs exceed distance 3.
example_3.py โ Single Node
$
Input:
root = [1], distance = 1
โบ
Output:
0
๐ก Note:
Only one node exists, so there are no pairs of different leaf nodes possible.
Constraints
- The number of nodes in the tree is in the range [1, 210]
- 1 โค Node.val โค 100
- 1 โค distance โค 10
- Each node value is unique
Visualization
Tap to expand
Understanding the Visualization
1
๐ Identify Leaves
Find all leaf nodes - these are the children who can form friendships
2
๐ Measure Distances
For each pair of leaves, calculate the path distance through their lowest common ancestor
3
โ
Count Valid Pairs
Count pairs where the total path distance is โค the given distance limit
4
โก Optimize with DFS
Use postorder traversal to count pairs efficiently in one pass
Key Takeaway
๐ฏ Key Insight: Instead of checking every leaf pair individually, we use postorder DFS to count valid pairs at their lowest common ancestor, achieving optimal efficiency with a single tree traversal.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code