Number of Good Leaf Nodes Pairs
Hard
Topics
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
null marks a missing child.Input: root = [1,2,3,null,4], distance = 3 Output: 1
Example 2
Input: root = [1,2,3,4,5,6,7], distance = 3 Output: 2
Example 3
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
- Return an empty list for a null node and
[0]for a leaf. - Recurse into both children to get their distance lists.
- For each pair across the two lists, count it when
left + right + 2 <= distance. - 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 edgesComplexity
- 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 sizedistance+1makes 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.cntimport java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int countPairs(TreeNode root, int k) {
cnt = 0;
bound = k;
dfs(root);
return cnt;
}
int cnt;
int bound;
private List<Integer> dfs(TreeNode node) {
int k = bound;
List<Integer> res = new ArrayList<>();
if (node == null) return res;
if (node.left == null && node.right == null) {
res.add(0);
return res;
}
List<Integer> L = dfs(node.left), R = dfs(node.right);
for (int x : L) for (int y : R) if (x + y + 2 <= k) cnt++;
for (int x : L) if (x + 1 <= k) res.add(x + 1);
for (int y : R) if (y + 1 <= k) res.add(y + 1);
return res;
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: int countPairs(TreeNode* root, int k) {
int cnt = 0;
function<vector<int>(TreeNode*)> dfs = [&](TreeNode* node) -> vector<int> {
vector<int> res;
if (!node) return res;
if (!node->left && !node->right) {
res.push_back(0);
return res;
}
vector<int> L = dfs(node->left), R = dfs(node->right);
for (int x : L) for (int y : R) if (x + y + 2 <= k) cnt++;
for (int x : L) if (x + 1 <= k) res.push_back(x + 1);
for (int y : R) if (y + 1 <= k) res.push_back(y + 1);
return res;
};
dfs(root);
return cnt;
}
};/** Tree node shape: { val, left, right } */ /**
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/ var countPairs = function(root, k) {
let cnt = 0;
const dfs = (node) => {
if (!node) return [];
if (!node.left && !node.right) return [0];
const L = dfs(node.left), R = dfs(node.right);
for (const x of L) for (const y of R) if (x + y + 2 <= k) cnt++;
const res = [];
for (const d of L.concat(R)) if (d + 1 <= k) res.push(d + 1);
return res;
};
dfs(root);
return cnt;
};