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
Number of Good Leaf Nodes Pairs INPUT Binary Tree Structure: 1 2 3 leaf 4 leaf null root = [1,2,3,null,4] distance = 3 ALGORITHM STEPS 1 DFS Traversal Post-order: visit children first, then parent 2 Collect Distances At leaves: return [1] (distance to parent) 3 Check Pairs For each node: compare left + right distances 4 Count Good Pairs If dist_l + dist_r <= distance: count++ Distance Calculation: Node 4 --> Node 2 = 1 Node 2 --> Node 1 = 1 Node 1 --> Node 3 = 1 Total: 3 <= 3 [OK] FINAL RESULT Good Pair Path Highlighted: 1 2 3 4 Path: 4 --> 2 --> 1 --> 3 Length = 3 Output 1 1 good leaf pair found Key Insight: DFS returns an array of distances from each leaf to the current node. At each internal node, we compare distances from left and right subtrees. If left_dist + right_dist <= distance, we found a good pair! Then increment all distances by 1 and propagate upward. TutorialsPoint - Number of Good Leaf Nodes Pairs | DFS with Distance Propagation
Asked in
Amazon 15 Google 12 Microsoft 8 Facebook 6
89.2K Views
Medium Frequency
~25 min Avg. Time
1.5K 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