var sumRootToLeaf = function (root) {
const ans = [];
dfs(root, []);
function dfs(root, path) {
if (root === null) {
return;
}
path = path.concat(root.val);
if (root.left === null && root.right === null) {
ans.push(path);
return;
}
dfs(root.left, path);
dfs(root.right, path);
}
return ans.reduce((acc, arr) => {
const len = arr.length - 1;
arr.forEach((val, i) => {
acc += val * 2 ** (len - i);
});
return acc;
}, 0);
};
var sumRootToLeaf = function (root) {
function dfs(node, currentSum) {
if (node === null) return 0;
currentSum = (currentSum << 1) | node.val;
if (node.left === null && node.right === null) {
return currentSum;
}
return dfs(node.left, currentSum) + dfs(node.right, currentSum);
}
return dfs(root, 0);
};