Skip to content

Commit 271b745

Browse files
authored
Merge pull request #38 from jeantimex/sum-root-to-leaf-numbers
Added sum root to leaf numbers problem.
2 parents 47cc65f + a36e375 commit 271b745

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ A collection of JavaScript problems and solutions for studying algorithms.
3434
- [Populating Next Right Pointers in Each Node](src/tree/populating-next-right-pointers-in-each-node.js)
3535
- [Populating Next Right Pointers in Each Node II](src/tree/populating-next-right-pointers-in-each-node-ii.js)
3636
- [Binary Tree Maximum Path Sum](src/tree/binary-tree-maximum-path-sum.js)
37+
- [Sum Root to Leaf Numbers](src/tree/sum-root-to-leaf-numbers.js)
3738

3839
### Dynamic Programming
3940

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { assert } from 'chai';
2+
import { serializeTree, deserializeTree } from 'utils/tree-util';
3+
import sumNumbers from '../sum-root-to-leaf-numbers';
4+
5+
describe('Sum Root to Leaf Numbers', () => {
6+
const testCases = [['null', 0], ['1', 1], ['1,2', 12], ['1,2,3', 25]];
7+
8+
testCases.map((testCase, index) => {
9+
it(`should calculate the sum from roof to leaf nodes for tree ${testCase[0]}`, () => {
10+
const root = deserializeTree(testCase[0]);
11+
const expected = testCase[1];
12+
const actual = sumNumbers(root);
13+
assert.equal(actual, expected);
14+
});
15+
});
16+
});

src/tree/sum-root-to-leaf-numbers.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
3+
*
4+
* An example is the root-to-leaf path 1->2->3 which represents the number 123.
5+
*
6+
* Find the total sum of all root-to-leaf numbers.
7+
*
8+
* For example,
9+
*
10+
* 1
11+
* / \
12+
* 2 3
13+
* The root-to-leaf path 1->2 represents the number 12.
14+
* The root-to-leaf path 1->3 represents the number 13.
15+
*
16+
* Return the sum = 12 + 13 = 25.
17+
*/
18+
19+
/**
20+
* @param {TreeNode} root
21+
* @return {number}
22+
*/
23+
const sumNumbers = root => {
24+
return helper(root, 0);
25+
};
26+
27+
const helper = (node, sum) => {
28+
if (!node) {
29+
return 0;
30+
}
31+
32+
const { left, right } = node;
33+
34+
sum = 10 * sum + node.val;
35+
36+
if (!left && !right) {
37+
return sum;
38+
}
39+
40+
return helper(left, sum) + helper(right, sum);
41+
};
42+
43+
export default sumNumbers;

0 commit comments

Comments
 (0)