-
Notifications
You must be signed in to change notification settings - Fork 0
/
1530. Number of Good Leaf Nodes Pairs
66 lines (51 loc) · 1.28 KB
/
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* 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
{
int result = 0;
public int countPairs(TreeNode root, int distance)
{
dfs(root, distance);
return result;
}
public int[] dfs(TreeNode root, int distance)
{
int[] d = new int[distance + 1]; // distance --> number of leaf nodes
if(root == null) return d;
if(root.left == null && root.right == null)
{
d[0] = 1;
return d;
}
int[] dl = dfs(root.left, distance);
int[] dr = dfs(root.right, distance);
for (int i = 0; i < distance; i++)
{
for (int j = 0; j < distance; j++)
{
if (i + j + 2 <= distance)
{
result += dl[i] * dr[j];
}
}
}
for (int i = 0; i < distance; ++i)
{
d[i + 1] = dl[i] + dr[i];
}
return d;
}
}