#C5207. Level Sum of Binary Tree
Level Sum of Binary Tree
Level Sum of Binary Tree
You are given a binary tree represented by its level-order traversal. Your task is to compute the sum of the nodes at each level of the tree. More formally, if the nodes at level ( i ) are denoted by ( n_1, n_2, \dots, n_k ), then the level sum ( S_i ) is given by
[ S_i = \sum_{j=1}^{k} n_j ]
Note that the binary tree may contain negative values and may be empty. The input is given as a single line of space-separated tokens. The token null
represents a missing node in the tree.
For example, the input
1 2 3 4 5 6 7
represents the following binary tree:
1
/ \
2 3
/ \ / \
4 5 6 7
and the level sums are: (1) for level 0, (2+3=5) for level 1, and (4+5+6+7=22) for level 2.
inputFormat
Input is provided via standard input (stdin) as a single line containing space-separated tokens representing the level-order traversal of the binary tree. Each token is either an integer or the string null
indicating that a node is missing. For example:
1 2 3 4 5 6 7
If the tree is empty, the input will be a single token null
.
outputFormat
Output the level sums of the binary tree as a single line on standard output (stdout). The sums for each level should be printed in order and separated by a single space. If the tree is empty, output an empty line.## sample
null