1530. Number of Good Leaf Nodes Pairs

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
class Solution {
private static class Pair {
private final List<Integer> leafDistanceList;
private int count;

public Pair() {
this.leafDistanceList = new ArrayList<>();
this.count = 0;
}
}

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

private Pair dfs(TreeNode root, int distance) {
Pair pair = new Pair();

if (root == null) {
return pair;
}
if (root.left == null && root.right == null) {
pair.leafDistanceList.add(0);
return pair;
}

Pair left = dfs(root.left, distance);
Pair right = dfs(root.right, distance);

pair.count += left.count + right.count;

for (int leftDistance : left.leafDistanceList) {
for (int rightDistance : right.leafDistanceList) {
if (leftDistance + rightDistance + 2 <= distance) {
pair.count += 1;
}
}
}

for (int leftDistance : left.leafDistanceList) {
pair.leafDistanceList.add(leftDistance + 1);
}
for (int rightDistance : right.leafDistanceList) {
pair.leafDistanceList.add(rightDistance + 1);
}

return pair;
}
}

使用后序遍历解题。

References

1530. Number of Good Leaf Nodes Pairs