-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNumberOfGoodLeafNodesPairs.java
57 lines (48 loc) · 1.47 KB
/
NumberOfGoodLeafNodesPairs.java
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.smlnskgmail.jaman.leetcodejava.medium;
import com.smlnskgmail.jaman.leetcodejava.support.TreeNode;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// https://leetcode.com/problems/number-of-good-leaf-nodes-pairs/
public class NumberOfGoodLeafNodesPairs {
private final TreeNode root;
private final int distance;
private int result;
public NumberOfGoodLeafNodesPairs(TreeNode root, int distance) {
this.root = root;
this.distance = distance;
}
public int solution() {
calculate(root, distance);
return result;
}
private List<Integer> calculate(TreeNode node, int distance) {
if (node == null) {
return Collections.emptyList();
}
if (node.left == null && node.right == null) {
return Collections.singletonList(1);
}
List<Integer> left = calculate(node.left, distance);
List<Integer> right = calculate(node.right, distance);
for (int l : left) {
for (int r : right) {
if (l + r <= distance) {
result++;
}
}
}
List<Integer> path = new ArrayList<>();
for (int l : left) {
if (l + 1 < distance) {
path.add(l + 1);
}
}
for (int r : right) {
if (r + 1 < distance) {
path.add(r + 1);
}
}
return path;
}
}