A warehouse rack is modeled as a binary tree hung over a set of vertical columns. The root sits in column 0; a left child sits one column to the left (column - 1) and a right child one column to the right (column + 1). For every column that contains at least one node, report the sum of the node values in that column. List the column totals from the left-most column to the right-most column.
Line 1: an integer n, the number of tokens on the next line.
Line 2: n space-separated tokens describing a binary tree in level-order (breadth-first). The first token is the root's value. Reading left to right, keep a queue of already-created nodes; for each node taken from the front of the queue, the next two tokens are its left child then its right child, where the token null marks a missing child. Only non-null children are added to the queue. Trailing null tokens for absent children at the deepest level may be omitted. Every node value is an integer.
A single line: the value total of each occupied column, ordered from the left-most column to the right-most, space-separated.
Example 1
Input
7 3 9 20 null null 15 7
Expected
9 18 20 7
Explanation
Columns: 9 at -1; 3 and 15 at 0 (sum 18); 20 at 1; 7 at 2. Left-to-right totals: 9 18 20 7.
Example 2
Input
4 1 2 null 3
Expected
3 2 1
Explanation
Node 1 is at column 0, node 2 at -1, node 3 at -2. Left-to-right totals: 3 2 1.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →