Skip to content

Commit 367facf

Browse files
authored
Create 1530. Number of Good Leaf Nodes Pairs (#533)
2 parents 47dbcb0 + b74ad09 commit 367facf

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

1530. Number of Good Leaf Nodes Pairs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
private:
3+
int count = 0;
4+
const int MAX_DISTANCE = 10;
5+
6+
vector<int> dfs(TreeNode* node, int distance) {
7+
if (!node) return vector<int>(MAX_DISTANCE + 1, 0);
8+
9+
if (!node->left && !node->right) {
10+
vector<int> res(MAX_DISTANCE + 1, 0);
11+
res[1] = 1;
12+
return res;
13+
}
14+
15+
vector<int> left = dfs(node->left, distance);
16+
vector<int> right = dfs(node->right, distance);
17+
18+
for (int i = 1; i <= distance; i++) {
19+
for (int j = 1; j <= distance - i; j++) {
20+
count += left[i] * right[j];
21+
}
22+
}
23+
24+
vector<int> res(MAX_DISTANCE + 1, 0);
25+
for (int i = 1; i < MAX_DISTANCE; i++) {
26+
res[i + 1] = left[i] + right[i];
27+
}
28+
29+
return res;
30+
}
31+
32+
public:
33+
int countPairs(TreeNode* root, int distance) {
34+
dfs(root, distance);
35+
return count;
36+
}
37+
};

0 commit comments

Comments
 (0)