File tree 1 file changed +37
-0
lines changed
1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments