1302. Deepest Leaves Sum
https://leetcode.com/problems/deepest-leaves-sum/
Python
Sum Levels with preorder travel
class Solution:
def deepestLeavesSum(self, root: Optional[TreeNode]) -> int:
level_counts = []
def preorder(node, level):
if not node:
return
if level == len(level_counts):
level_counts.append(0)
level_counts[level] += node.val
preorder(node.left, level+1)
preorder(node.right, level+1)
preorder(root, 0)
return level_counts[-1]
Javascript
var deepestLeavesSum = function(root) {
const queue = [root];
let level = 0;
const layer = [];
while (queue.length) {
const total = queue.length;
layer.push([]);
for (let i = 0; i < total; i++) {
const node = queue.shift();
layer[level].push(node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
level++;
}
return layer[layer.length - 1].reduce((acc, cur) => acc + cur, 0)
}