Skip to main content
LeetCode 1530, Medium. Topics: Tree, Depth-First Search, Binary Tree, DP on Trees. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 18 parametrized pytest cases, and a playground notebook:

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.

Examples

Example 1
Explanation: The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair. Example 2
Explanation: The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of the shortest path between them is 4.
Explanation: The only good pair is [2,5].

Constraints

  • The number of nodes in the tree is in the range [1, 2^10].
  • 1 <= Node.val <= 100
  • 1 <= distance <= 10

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026