All problems

Problem 401

Level Sums of a Binary Tree

Easy · 10 pts · Tree, Breadth-First Search, Binary Tree

Problem

For each level of a binary tree, from the root level downwards, print the sum of the values on that level. The root is alone on level 1, its children form level 2, their children level 3, and so on. A breadth-first traversal visits the tree level by level, which makes the sums easy to collect.

Input

The first line contains N, the number of tokens. The second line contains N tokens describing the tree in level order (breadth-first, left to right), where 'null' marks a missing child, as on LeetCode.

Output

Print one sum per level, from top to bottom, separated by spaces.

Constraints

1 <= number of nodes <= 10000; -1000 <= value <= 1000

Example input

7
3 9 20 null null 15 7

Example output

3 29 22

Explanation

The tree 3 / 9 20 / 15 7 has level sums 3, then 9 + 20 = 29, then 15 + 7 = 22.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Frequency Stack Next: Largest Value in Each Row