Skip to content

Commit 2451db4

Browse files
authored
Create 113-path-sum-ii.js
1 parent cb5db18 commit 2451db4

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

113-path-sum-ii.js

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {TreeNode} root
10+
* @param {number} sum
11+
* @return {number[][]}
12+
*/
13+
14+
const pathSum = function(root, sum) {
15+
const result = [];
16+
backtrack(root, sum, [], result);
17+
return result;
18+
};
19+
20+
const backtrack = function(root, sum, temp, result) {
21+
if (root == null) {
22+
return;
23+
}
24+
temp.push(root.val);
25+
let newSum = sum - root.val;
26+
if (root.left == null && root.right == null) {
27+
if (newSum === 0) {
28+
result.push([...temp]);
29+
}
30+
temp.pop();
31+
return;
32+
}
33+
backtrack(root.left, newSum, temp, result);
34+
backtrack(root.right, newSum, temp, result);
35+
temp.pop();
36+
}

0 commit comments

Comments
 (0)