Skip to content

Commit 4cacbee

Browse files
committed
Path Sum II
1 parent c921be2 commit 4cacbee

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
|110|[平衡二叉树](https://leetcode.cn/problems/balanced-binary-tree/)|[JavaScript](./algorithms/balanced-binary-tree.js)|Easy|
2727
|111|[二叉树的最小深度](https://leetcode.cn/problems/minimum-depth-of-binary-tree/)|[JavaScript](./algorithms/minimum-depth-of-binary-tree.js)|Easy|
2828
|112|[路径总和](https://leetcode.cn/problems/path-sum/)|[JavaScript](./algorithms/path-sum.js)|Easy|
29+
|113|[路径总和 II](https://leetcode.cn/problems/path-sum-ii/)|[JavaScript]()|Medium|
2930
|136|[只出现一次的数字](https://leetcode-cn.com/problems/single-number/)|[JavaScript](./algorithms/single-number.js)|Easy|
3031
|141|[环形链表](https://leetcode-cn.com/problems/linked-list-cycle/)|[JavaScript](./algorithms/linked-list-cycle.js)|Easy|
3132
|142|[环形链表 II](https://leetcode.cn/problems/linked-list-cycle-ii/)|[JavaScript](./algorithms/linked-list-cycle-ii.js)|Medium|

algorithms/path-sum-ii.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* 路径总和 II
11+
* @param {TreeNode} root
12+
* @param {number} targetSum
13+
* @return {number[][]}
14+
*/
15+
var pathSum = function (root, targetSum) {
16+
const arr = [];
17+
const result = [];
18+
19+
const dfs = (node, sum) => {
20+
if (node) {
21+
arr.push(node.val);
22+
if (!node.left && !node.right && node.val === sum) {
23+
result.push([...arr]);
24+
}
25+
dfs(node.left, sum - node.val);
26+
dfs(node.right, sum - node.val);
27+
arr.pop();
28+
}
29+
};
30+
31+
dfs(root, targetSum);
32+
33+
return result;
34+
};

0 commit comments

Comments
 (0)