dfs
/**
* 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) {
if (!root) return root
let arr = []
let result = 0
let dfs = (data, presum) => {
if (data) {
presum = data.val + presum * 10
if (!data.left && !data.right)
arr.push(presum)
else {
dfs(data.left, presum)
dfs(data.right, presum)
}
}
}
dfs(root, 0)
result = arr.reduce((a, b) => {return a + b})
return result
};
优化一下得到:
/**
* 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 dfs = (data, presum) => {
if (data === null) return 0
presum = data.val + presum * 10
if (!data.left && !data.right) {
return presum
}
return dfs(data.left, presum) + dfs(data.right, presum)
}
return dfs(root, 0)
};