forked from adamespii/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem_125.js
40 lines (35 loc) Β· 807 Bytes
/
problem_125.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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
/**
* Finds two nodes that equal k
* @param {TreeNode} root
* @param {number} k
* @return {TreeNode[]}
*/
function binaryTreeSum(root, k) {
const map = new Map();
return findPair(root, k, map);
}
/**
*
* @param {TreeNode} root
* @param {number} k
* @param {Map<number,TreeNode>} map
* @return {TreeNode[]}
*/
function findPair(root, k, map) {
if (root === null) return [];
// Retrieve companion node
if (map.has(k - root.val)) {
return [map.get(root.val), map.get(k - root.val)];
}
// Ignoring duplicate value nodes
map.set(root.val, root);
findPair(root.left, k, map); // 5
findPair(root.right, k, map); // 15
return [];
}