Forgetting null/base-case handling
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.
Move from brute-force thinking to an efficient approach using tree strategy.
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.
Example 1:
Input: root = [1,2,3,null,4], distance = 3 Output: 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:
Input: root = [1,2,3,4,5,6,7], distance = 3 Output: 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 ther shortest path between them is 4.
Example 3:
Input: root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3 Output: 1 Explanation: The only good pair is [2,5].
Constraints:
tree is in the range [1, 210].1 <= Node.val <= 1001 <= distance <= 10Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Tree
[1,2,3,null,4] 3
[1,2,3,4,5,6,7] 3
[7,1,4,6,null,5,3,null,null,null,null,null,2] 3
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1530: Number of Good Leaf Nodes Pairs
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int countPairs(TreeNode root, int distance) {
if (root == null) {
return 0;
}
int ans = countPairs(root.left, distance) + countPairs(root.right, distance);
int[] cnt1 = new int[distance];
int[] cnt2 = new int[distance];
dfs(root.left, cnt1, 1);
dfs(root.right, cnt2, 1);
for (int i = 0; i < distance; ++i) {
for (int j = 0; j < distance; ++j) {
if (i + j <= distance) {
ans += cnt1[i] * cnt2[j];
}
}
}
return ans;
}
void dfs(TreeNode root, int[] cnt, int i) {
if (root == null || i >= cnt.length) {
return;
}
if (root.left == null && root.right == null) {
++cnt[i];
return;
}
dfs(root.left, cnt, i + 1);
dfs(root.right, cnt, i + 1);
}
}
// Accepted solution for LeetCode #1530: Number of Good Leaf Nodes Pairs
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func countPairs(root *TreeNode, distance int) int {
if root == nil {
return 0
}
ans := countPairs(root.Left, distance) + countPairs(root.Right, distance)
cnt1 := make([]int, distance)
cnt2 := make([]int, distance)
dfs(root.Left, cnt1, 1)
dfs(root.Right, cnt2, 1)
for i, v1 := range cnt1 {
for j, v2 := range cnt2 {
if i+j <= distance {
ans += v1 * v2
}
}
}
return ans
}
func dfs(root *TreeNode, cnt []int, i int) {
if root == nil || i >= len(cnt) {
return
}
if root.Left == nil && root.Right == nil {
cnt[i]++
return
}
dfs(root.Left, cnt, i+1)
dfs(root.Right, cnt, i+1)
}
# Accepted solution for LeetCode #1530: Number of Good Leaf Nodes Pairs
# Definition for a binary tree node.
# 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: TreeNode, distance: int) -> int:
def dfs(root, cnt, i):
if root is None or i >= distance:
return
if root.left is None and root.right is None:
cnt[i] += 1
return
dfs(root.left, cnt, i + 1)
dfs(root.right, cnt, i + 1)
if root is None:
return 0
ans = self.countPairs(root.left, distance) + self.countPairs(
root.right, distance
)
cnt1 = Counter()
cnt2 = Counter()
dfs(root.left, cnt1, 1)
dfs(root.right, cnt2, 1)
for k1, v1 in cnt1.items():
for k2, v2 in cnt2.items():
if k1 + k2 <= distance:
ans += v1 * v2
return ans
// Accepted solution for LeetCode #1530: Number of Good Leaf Nodes Pairs
struct Solution;
use rustgym_util::*;
trait Postorder {
fn postorder(self, all: &mut usize, distance: i32) -> [usize; 10];
}
impl Postorder for TreeLink {
fn postorder(self, all: &mut usize, distance: i32) -> [usize; 10] {
if let Some(node) = self {
let mut res = [0; 10];
let mut node = node.borrow_mut();
let mut left = node.left.take();
let mut right = node.right.take();
if let (None, None) = (left.as_mut(), right.as_mut()) {
res[0] = 1;
} else {
let l = left.postorder(all, distance);
let r = right.postorder(all, distance);
for i in 0..9 {
for j in 0..9 {
if i + j <= (distance - 2) as usize {
*all += l[i] * r[j];
}
}
}
for i in 0..9 {
res[i + 1] += l[i];
}
for i in 0..9 {
res[i + 1] += r[i];
}
}
res
} else {
[0; 10]
}
}
}
impl Solution {
fn count_pairs(root: TreeLink, distance: i32) -> i32 {
let mut res = 0;
if distance < 2 {
return 0;
}
root.postorder(&mut res, distance);
res as i32
}
}
#[test]
fn test() {
let root = tree!(1, tree!(2, None, tree!(4)), tree!(3));
let distance = 3;
let res = 1;
assert_eq!(Solution::count_pairs(root, distance), res);
let root = tree!(
1,
tree!(2, tree!(4), tree!(5)),
tree!(3, tree!(6), tree!(7))
);
let distance = 3;
let res = 2;
assert_eq!(Solution::count_pairs(root, distance), res);
}
// Accepted solution for LeetCode #1530: Number of Good Leaf Nodes Pairs
function countPairs(root: TreeNode | null, distance: number): number {
const pairs: number[][] = [];
const dfs = (node: TreeNode | null): number[][] => {
if (!node) return [];
if (!node.left && !node.right) return [[node.val, 1]];
const left = dfs(node.left);
const right = dfs(node.right);
for (const [x, dx] of left) {
for (const [y, dy] of right) {
if (dx + dy <= distance) {
pairs.push([x, y]);
}
}
}
const res: number[][] = [];
for (const arr of [left, right]) {
for (const x of arr) {
if (++x[1] <= distance) res.push(x);
}
}
return res;
};
dfs(root);
return pairs.length;
}
Use this to step through a reusable interview workflow for this problem.
BFS with a queue visits every node exactly once — O(n) time. The queue may hold an entire level of the tree, which for a complete binary tree is up to n/2 nodes = O(n) space. This is optimal in time but costly in space for wide trees.
Every node is visited exactly once, giving O(n) time. Space depends on tree shape: O(h) for recursive DFS (stack depth = height h), or O(w) for BFS (queue width = widest level). For balanced trees h = log n; for skewed trees h = n.
Review these before coding to avoid predictable interview regressions.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.