Embercode
✕
Binary TreesCoding problems

Binary Trees: coding problems

Write a program that reads the input and prints the answer. Run checks it against every test, including hidden ones.

0 of 7 solved

  • A warehouse stores boxes in a binary tree. Each box holds some number of items, and the tree is written as a line of values in level order: the root first, then each level from left to right. The value -1 marks a missing child. Add up the items in every box.

    Read the whole input with cin. Use recursion: an empty tree adds 0, and any other node adds its own value to the sums of its two subtrees.

    Constraints: at most 1000 values, each from 0 to 999. The line -1 alone is an empty tree.

    Input. One line of level-order values, separated by spaces. Missing children are -1.

    Output. One integer: the sum of all values in the tree.

    Example 1 input

    1 2 3 4 5 -1 6
    

    Output

    21
    

    Example 2 input

    -1
    

    Output

    0