Skip to content

Commit d08c055

Browse files
committed
Add solution #112
1 parent bca70d0 commit d08c055

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444
102|[Binary Tree Level Order Traversal](./0102-binary-tree-level-order-traversal.js)|Medium|
4545
104|[Maximum Depth of Binary Tree](./0104-maximum-depth-of-binary-tree.js)|Easy|
4646
111|[Minimum Depth of Binary Tree](./0111-minimum-depth-of-binary-tree.js)|Easy|
47+
112|[Path Sum](./0112-path-sum.js)|Easy|
4748
118|[Pascal's Triangle](./0118-pascals-triangle.js)|Easy|
4849
119|[Pascal's Triangle II](./0119-pascals-triangle-ii.js)|Easy|
4950
121|[Best Time to Buy and Sell Stock](./0121-best-time-to-buy-and-sell-stock.js)|Easy|

solutions/0112-path-sum.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* 112. Path Sum
3+
* https://leetcode.com/problems/path-sum/
4+
* Difficulty: Easy
5+
*
6+
* Given the root of a binary tree and an integer targetSum, return true if the
7+
* tree has a root-to-leaf path such that adding up all the values along the
8+
* path equals targetSum.
9+
*
10+
* A leaf is a node with no children.
11+
*/
12+
13+
/**
14+
* Definition for a binary tree node.
15+
* function TreeNode(val, left, right) {
16+
* this.val = (val===undefined ? 0 : val)
17+
* this.left = (left===undefined ? null : left)
18+
* this.right = (right===undefined ? null : right)
19+
* }
20+
*/
21+
/**
22+
* @param {TreeNode} root
23+
* @param {number} targetSum
24+
* @return {boolean}
25+
*/
26+
var hasPathSum = function(root, targetSum) {
27+
if (!root) {
28+
return false;
29+
}
30+
const result = [];
31+
32+
traverse(result, root);
33+
34+
return result.includes(targetSum);
35+
};
36+
37+
function traverse(result, node, sum = 0) {
38+
if (!node.left && !node.right) {
39+
result.push(sum + node.val);
40+
}
41+
42+
if (node.left) traverse(result, node.left, sum + node.val);
43+
if (node.right) traverse(result, node.right, sum + node.val);
44+
}

0 commit comments

Comments
 (0)