-
-
Notifications
You must be signed in to change notification settings - Fork 8.6k
/
Copy pathSolution.js
45 lines (38 loc) · 1.03 KB
/
Solution.js
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
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} distance
* @return {number}
*/
var countPairs = function (root, distance) {
const pairs = [];
const dfs = node => {
if (!node) return [];
if (!node.left && !node.right) return [[node.val, 1]];
const left = dfs(node.left);
const right = dfs(node.right);
for (const [x, dx] of left) {
for (const [y, dy] of right) {
if (dx + dy <= distance) {
pairs.push([x, y]);
}
}
}
const res = [];
for (const arr of [left, right]) {
for (const x of arr) {
if (++x[1] <= distance) res.push(x);
}
}
return res;
};
dfs(root);
return pairs.length;
};