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
Good Leaf Node Pairs AlgorithmRootABL1L2L3L4LEAFLEAFLEAFLEAFDistance = 2Distance = 2Distance = 4Postorder DFS:1. Visit leaves first2. Count pairs at LCA3. Propagate distances up4. Return total countDistance Calculation:Path = Left + Right + 2L1โ†”L2: 1 + 1 + 0 = 2 โœ“L3โ†”L4: 1 + 1 + 0 = 2 โœ“L2โ†”L3: 2 + 2 + 0 = 4Complexity:Time: O(n ร— dยฒ)Space: O(n ร— d)n = nodesd = distance limitFor distance=3:Valid pairs:(L1,L2) โœ“(L3,L4) โœ“Result: 2
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.
Asked in
Amazon 25 Google 18 Microsoft 12 Meta 8
42.5K Views
Medium Frequency
~15 min Avg. Time
1.6K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen