Number of Good Leaf Nodes Pairs

Hard

Topics
TreeDFS

Given the root of a binary tree and an integer distance, a pair of two different leaf nodes is good if the length of the shortest path between them (in edges) is less than or equal to distance. Return the number of good leaf node pairs.

Example 1

2413
a good pair
Two leaves are good when the path between them has at most 3 edges. Rather than measuring every pair, each node collects the depths of the leaves below it and pairs across its two children — the shortest path between two leaves always bends at their lowest common ancestor. 1 pairs here.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [1,2,3,null,4], distance = 3
Output: 1

Example 2

4251637
leafa good pair
Input:  root = [1,2,3,4,5,6,7], distance = 3
Output: 2

Example 3

617543
leafa good pair
Input:  root = [7,1,4,6,null,5,3,null,null,null,null,null,null,2], distance = 3
Output: 1

Constraints

  • 1 <= number of nodes <= 2^10
  • 1 <= Node.val <= 100
  • 1 <= distance <= 10.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Two leaves' shortest path runs up to their lowest common ancestor and back down. So fix a node as that ancestor: any leaf below its left child paired with any leaf below its right child meets there, and the distance is the sum of the two depths plus the two edges into the children.

That makes the natural return value a list of distances to the leaves below this node. At each node, cross the left list against the right list and count the pairs whose combined distance fits the budget; then return the merged list with every distance incremented by one, dropping any that already exceed the budget since they can never contribute higher up.

The pruning is what keeps the lists short in practice, and it is also what makes the correctness argument clean: every pair is counted exactly once, at its lowest common ancestor.

Approach

  1. Return an empty list for a null node and [0] for a leaf.
  2. Recurse into both children to get their distance lists.
  3. For each pair across the two lists, count it when left + right + 2 <= distance.
  4. Return the merged lists with each value incremented, discarding values that exceed the budget.

Dry Run

      1
     / \
    2   3
   /
  4

leaves are 4 and 3

node 4 (leaf)   returns [0]
node 2          left [0], right [] -- no cross pairs
                returns [1]
node 3 (leaf)   returns [0]
node 1          left [1], right [0]
                pair distance 1 + 0 + 2 = 3

  distance = 1  ->  0 pairs    3 > 1
  distance = 2  ->  0 pairs    3 > 2
  distance = 3  ->  1 pair     3 <= 3

the path is 4 -> 2 -> 1 -> 3, which is three edges

Complexity

  • Time — O(n²) in the worst case: the cross product at a node is |left| × |right|, and those lists can hold O(n) entries each. Because the budget is at most 10, bucketing the distances into an array of size distance+1 makes each cross product O(distance²) and the whole thing O(n · distance²) — the better answer once the list version is on the board.
  • Space — O(n) for the lists in flight plus O(h) of recursion. At the stated bound of 2¹⁰ nodes a degenerate path needs 1,024 frames, which just exceeds Python's default limit of 1,000; the harness on this page raises it.

Common Pitfalls

  • Counting a pair at every common ancestor rather than the lowest one. Crossing only the left list against the right list at each node is what restricts it to the lowest.
  • Forgetting the + 2. The two edges from the node down into its children are part of the path.
  • Including same-side pairs. Two leaves under the same child meet lower down and are counted there.
  • Returning the distances without incrementing, so the parent underestimates every path by one level.
  • Pruning with < instead of <=, which drops distances that are still usable exactly at the budget.
  • Collecting all leaves and comparing every pair via their root paths. That is O(leaves² · height) and is the version this replaces — worth naming as the baseline.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def countPairs(self, root, k):
        self.cnt = 0
        def dfs(node):
            if not node: return []
            if not node.left and not node.right: return [0]
            L = dfs(node.left); R = dfs(node.right)
            for x in L:
                for y in R:
                    if x + y + 2 <= k: self.cnt += 1
            res = []
            for d in L + R:
                if d + 1 <= k: res.append(d + 1)
            return res
        dfs(root)
        return self.cnt
SensAI
Beta
Tap the mic to stop voice mode