A binary tree is given as a single space-separated level-order array. Values appear top-to-bottom, left-to-right, and the literal token null marks a missing child (a null never has children of its own). An empty tree is encoded as the single token null.
Compute the sum of the values of all real nodes in the tree. The sum of an empty tree is 0.
Values may be negative, so the answer can be negative; with up to 100000 nodes the total can exceed 32 bits, so accumulate in a 64-bit-safe integer.
A single line of level-order tokens separated by single spaces. Each token is an integer or the literal null. The line may be exactly null for an empty tree.
A single integer: the sum of all node values.
Small tree
Input
1 2 3
Expected
6
Explanation
The three node values are 1, 2, and 3, whose sum is 6.
Negatives and a gap
Input
-5 3 null -2
Expected
-4
Explanation
Node values are -5 (root), 3 (left child), and -2 (right child of node 3); the `null` marks a missing left child of node 3. The sum is -5 + 3 + (-2) = -4.
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 →