Skip to content

Commit adceb56

Browse files
authored
Create 129-sum-root-to-leaf-numbers.js
1 parent 0e4114a commit adceb56

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

129-sum-root-to-leaf-numbers.js

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {TreeNode} root
10+
* @return {number}
11+
*/
12+
const sumNumbers = function(root) {
13+
const sum = []
14+
rec(root, '', sum)
15+
return sum.reduce((ac, el) => ac + el, 0)
16+
};
17+
18+
function rec(node, str, arr) {
19+
if (node == null) {
20+
arr.push(+str)
21+
return
22+
}
23+
if (node.left !== null) {
24+
rec(node.left, str + node.val, arr)
25+
}
26+
if (node.right !== null) {
27+
rec(node.right, str + node.val, arr)
28+
}
29+
if (node.left === null && node.right === null) {
30+
arr.push(+(str + node.val) )
31+
}
32+
}

0 commit comments

Comments
 (0)