-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy path129.sum-root-to-leaf-numbers.js
More file actions
43 lines (40 loc) · 958 Bytes
/
129.sum-root-to-leaf-numbers.js
File metadata and controls
43 lines (40 loc) · 958 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
* @lc app=leetcode.cn id=129 lang=javascript
*
* [129] Sum Root to Leaf Numbers
*/
// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* let ans = [];
function bst(node) {
ans.push(node.val);
if (node.left) bst(node.left)
if (node.right) bst(node.right)
}
bst(root);
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var sumNumbers = function(root) {
let sum = 0;
const bst = (current, node) => {
if (!node) return;
if (!node.left && !node.right) {
sum += (current + node.val) * 1;
return;
}
bst(current + node.val, node.left);
bst(current + node.val, node.right);
}
bst('', root);
return sum;
};
// @lc code=end