Skip to content

Commit 2a5b857

Browse files
authored
Merge pull request #32 from jeantimex/path-sum
Added path sum.
2 parents 3584d61 + f48be5f commit 2a5b857

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ A collection of JavaScript problems and solutions for studying algorithms.
2828
- [Convert Sorted Array to Binary Search Tree](src/tree/convert-sorted-array-to-binary-search-tree.js)
2929
- [Balanced Binary Tree](src/tree/balanced-binary-tree.js)
3030
- [Minimum Depth of Binary Tree](src/tree/minimum-depth-of-binary-tree.js)
31+
- [Path Sum](src/tree/path-sum.js)
3132

3233
### Dynamic Programming
3334

src/tree/__tests__/path-sum-test.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { assert } from 'chai';
2+
import { serializeTree, deserializeTree } from 'utils/tree-util';
3+
import hasPathSum from '../path-sum';
4+
5+
describe('Path Sum', () => {
6+
const testCases = [
7+
['', 0, false],
8+
['5,4,8,11,null,13,4,7,2,null,null,null,1', 22, true],
9+
['1', 0, false],
10+
['1', 1, true],
11+
['1,2', 3, true],
12+
['1,null,2', 3, true],
13+
];
14+
15+
testCases.map((testCase, index) => {
16+
it(`should validate if there's a path for ${testCase[0]}`, () => {
17+
const root = deserializeTree(testCase[0]);
18+
const sum = testCase[1];
19+
const expected = testCase[2];
20+
const actual = hasPathSum(root, sum);
21+
assert.equal(actual, expected);
22+
});
23+
});
24+
});

src/tree/path-sum.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Given a binary tree and a sum, determine if the tree has a root-to-leaf path such
3+
* that adding up all the values along the path equals the given sum.
4+
*
5+
* For example:
6+
* Given the below binary tree and sum = 22,
7+
* 5
8+
* / \
9+
* 4 8
10+
* / / \
11+
* 11 13 4
12+
* / \ \
13+
* 7 2 1
14+
* return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
15+
*/
16+
17+
/**
18+
* @param {TreeNode} root
19+
* @param {number} sum
20+
* @return {boolean}
21+
*/
22+
const hasPathSum = (root, sum) => {
23+
if (!root) {
24+
return false;
25+
}
26+
27+
if (!root.left && !root.right) {
28+
return root.val === sum;
29+
}
30+
31+
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
32+
};
33+
34+
export default hasPathSum;

0 commit comments

Comments
 (0)