https://leetcode.com/problems/sum-root-to-leaf-numbers/?envType=daily-question&envId=2024-04-15
/**
* 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
let sum = 0
function dfs(node, currentSum) {
if (!node) return
currentSum = (currentSum * 10) + node.val
if (!node.right && !node.left) {
sum += currentSum
return
}
dfs(node.right, currentSum)
dfs(node.left, currentSum)
}
dfs(root, 0)
return sum
};
Top comments (0)