-
Notifications
You must be signed in to change notification settings - Fork 0
/
129.求根节点到叶节点数字之和.js
44 lines (40 loc) · 914 Bytes
/
129.求根节点到叶节点数字之和.js
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
44
/*
* @lc app=leetcode.cn id=129 lang=javascript
*
* [129] 求根节点到叶节点数字之和
*/
const { traverse } = require('@babel/core')
// @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)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var sumNumbers = function(root) {
let sum = 0
const path = []
traverse(root)
return sum
function traverse(root) {
if (!root) return
path.push(root.val)
if (!root.left && !root.right) {
const pathSum = path.reduce(
(accu, cur, i) => accu + cur * Math.pow(10, path.length - 1 - i),
0
)
sum += pathSum
}
traverse(root.left)
traverse(root.right)
path.pop()
}
}
// @lc code=end