[Leetcode] Problem 1530 - Number of Good Leaf Nodes Pairs

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

No.1

0y8N5t.jpg

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.

No.2

0y8w28.jpg

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.

No.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].

No.4

Input: root = [100], distance = 1

Output: 0

No.5

Input: root = [1,1,1], distance = 2

Output: 1

Constraints

  • The number of nodes in the tree is in the range [1, 2^10].
  • Each node’s value is between [1, 100].
  • 1 <= distance <= 10

Code

1
2
3
4
5
6
7
8
9
10
11
12
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;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
private int result = 0;

public int countPairs(TreeNode root, int distance) {
dfs(root, distance);
return result;
}

private int[] dfs(TreeNode root, int dist) {
int[] distances = new int[dist + 1];

if (root == null)
return distances;

if (root.left == null && root.right == null) {
distances[0] = 1;
return distances;
}

int[] left = dfs(root.left, dist);
int[] right = dfs(root.right, dist);

for (int i = 0; i < left.length; i++) {
for (int j = 0; j < right.length; j++) {
if (i + j + 2 <= dist)
result += left[i] * right[j];
}
}

for (int i = 0; i < distances.length - 1; i++)
distances[i + 1] = left[i] + right[i];

return distances;
}