-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.js
41 lines (41 loc) · 1.04 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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {number} sum
* @return {number[][]}
*/
// DFS 有点回溯类问题的味道
var pathSum = function (root, sum) {
if (!root) {
return [];
}
const sequences = [];
function helper (node, arr, cur) {
// leaf node
if (!node.left && !node.right) {
if (node.val + cur === sum) {
arr.push(node.val);
sequences.push(arr);
}
return;
}
if (!node.left) {
arr.push(node.val);
return helper(node.right, arr, cur + node.val);
}
if (!node.right) {
arr.push(node.val);
return helper(node.left, arr, cur + node.val);
}
helper(node.left, arr.concat(node.val), cur + node.val);
helper(node.right, arr.concat(node.val), cur + node.val);
}
helper(root, [], 0);
return sequences;
};