Skip to content

Commit f7c0b82

Browse files
committed
Add solution #113
1 parent 8251bd3 commit f7c0b82

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@
106106
110|[Balanced Binary Tree](./0110-balanced-binary-tree.js)|Easy|
107107
111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy|
108108
112|[Path Sum](./0112-path-sum.js)|Easy|
109+
113|[Path Sum II](./0113-path-sum-ii.js)|Medium|
109110
116|[Populating Next Right Pointers in Each Node](./0116-populating-next-right-pointers-in-each-node.js)|Medium|
110111
118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy|
111112
119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy|

solutions/0113-path-sum-ii.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* 113. Path Sum II
3+
* https://leetcode.com/problems/path-sum-ii/
4+
* Difficulty: Medium
5+
*
6+
* Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where
7+
* the sum of the node values in the path equals targetSum. Each path should be returned as a
8+
* list of the node values, not node references.
9+
*
10+
* A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a
11+
* node with no children.
12+
*/
13+
14+
/**
15+
* Definition for a binary tree node.
16+
* function TreeNode(val, left, right) {
17+
* this.val = (val===undefined ? 0 : val)
18+
* this.left = (left===undefined ? null : left)
19+
* this.right = (right===undefined ? null : right)
20+
* }
21+
*/
22+
/**
23+
* @param {TreeNode} root
24+
* @param {number} targetSum
25+
* @return {number[][]}
26+
*/
27+
var pathSum = function(root, targetSum) {
28+
if (!root) return [];
29+
return traverse([], targetSum, root);
30+
};
31+
32+
function traverse(result, targetSum, node, history = []) {
33+
const values = [...history, node.val];
34+
35+
if (!node.left && !node.right && values.reduce((sum, n) => sum + n, 0) === targetSum) {
36+
result.push(values);
37+
}
38+
39+
if (node.left) traverse(result, targetSum, node.left, values);
40+
if (node.right) traverse(result, targetSum, node.right, values);
41+
42+
return result;
43+
}

0 commit comments

Comments
 (0)