Given the root of a binary tree, return the sum of the nodes at each level. The output should be a list containing the sum of the nodes at each level.
Example 1
Input:
[1, 3, 4, null, 2, 7, null, 8]
Output: [1, 7, 9, 8]
Example 2
Input:
[1, 2, 5, 3, null, null, null, null, 4]
Output: [1, 7, 3, 4]
Explanation
We should recognize that a level-order breadth-first traversal of the binary tree is the most straightforward way to solve this problem.
At each level, we can keep a running sum of the node’s values at that level. Then, whenever we finish processing a level (the for-loop for that level finishes), then we can add the sum of the nodes to the output list.
class Solution: def levelSum(self, root: TreeNode) -> List[int]: if not root: return [] nodes = [] queue = deque([root]) while queue: # start of a new level here level_size = len(queue) sum_ = 0 # process all nodes in the current level for i in range(level_size): node = queue.popleft() sum_ += node.val if node.left: queue.append(node.left) if node.right: queue.append(node.right) # we are at the end of the level, # add the sum of the nodes to the output list nodes.append(sum_) return nodes
class Solution { public List<Integer> levelSum(TreeNode root) { if (root == null) { return new ArrayList<>(); } List<Integer> nodes = new ArrayList<>(); Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { // start of a new level here int levelSize = queue.size(); int sum = 0; // process all nodes in the current level for (int i = 0; i < levelSize; i++) { TreeNode node = queue.poll(); sum += node.val; if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } } // we are at the end of the level, // add the sum of the nodes to the output list nodes.add(sum); } return nodes; }}
func levelSum(root *TreeNode) []int { if root == nil { return []int{} } var nodes []int queue := []*TreeNode{root} for len(queue) > 0 { // start of a new level here levelSize := len(queue) sum := 0 // process all nodes in the current level for i := 0; i < levelSize; i++ { node := queue[0] queue = queue[1:] sum += node.Val if node.Left != nil { queue = append(queue, node.Left) } if node.Right != nil { queue = append(queue, node.Right) } } // we are at the end of the level, // add the sum of the nodes to the output list nodes = append(nodes, sum) } return nodes}
class Solution { levelSum(root: TreeNode | null): number[] { if (!root) { return []; } const nodes: number[] = []; const queue: TreeNode[] = [root]; while (queue.length > 0) { // start of a new level here const levelSize = queue.length; let sum = 0; // process all nodes in the current level for (let i = 0; i < levelSize; i++) { const node = queue.shift()!; sum += node.val; if (node.left) { queue.push(node.left); } if (node.right) { queue.push(node.right); } } // we are at the end of the level, // add the sum of the nodes to the output list nodes.push(sum); } return nodes; }}