Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit e9fbc43

Browse files
committedFeb 7, 2025
Add solution #437
1 parent 5d514fd commit e9fbc43

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,7 @@
252252
415|[Add Strings](./0415-add-strings.js)|Easy|
253253
419|[Battleships in a Board](./0419-battleships-in-a-board.js)|Medium|
254254
435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium|
255+
437|[Path Sum III](./0437-path-sum-iii.js)|Medium|
255256
442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium|
256257
443|[String Compression](./0443-string-compression.js)|Medium|
257258
448|[Find All Numbers Disappeared in an Array](./0448-find-all-numbers-disappeared-in-an-array.js)|Easy|

‎solutions/0437-path-sum-iii.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* 437. Path Sum III
3+
* https://leetcode.com/problems/path-sum-iii/
4+
* Difficulty: Medium
5+
*
6+
* Given the root of a binary tree and an integer targetSum, return the number of paths where the
7+
* sum of the values along the path equals targetSum.
8+
*
9+
* The path does not need to start or end at the root or a leaf, but it must go downwards
10+
* (i.e., traveling only from parent nodes to child nodes).
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} sum
24+
* @return {number}
25+
*/
26+
var pathSum = function(root, sum) {
27+
if (!root) return 0;
28+
return (subPathSum(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum));
29+
};
30+
31+
function subPathSum(node, sum) {
32+
if (!node) return 0;
33+
const self = node.val === sum ? 1 : 0;
34+
return self + subPathSum(node.left, sum - node.val) + subPathSum(node.right, sum - node.val);
35+
}

0 commit comments

Comments
 (0)
Please sign in to comment.