#K74897. Sum of Nodes at a Given Depth

    ID: 34299 Type: Default 1000ms 256MiB

Sum of Nodes at a Given Depth

Sum of Nodes at a Given Depth

You are given a binary tree represented in level order and an integer \(d\) representing a depth in the tree (with the root at depth 0). Your task is to compute the sum of all node values at depth \(d\). If there are no nodes at that depth, return 0.

The binary tree is provided as a series of tokens separated by spaces. Each token represents a node's value. The token null indicates that a node is missing.

Example:

Input:
1 2 3 4 5 6 7
2

Output: 22

</p>

Here, the tree constructed from the tokens is:

        1
       / \
      2   3
     / \ / \
    4  5 6  7

At depth \(2\), the nodes are 4, 5, 6, and 7, and their sum is \(4+5+6+7=22\).

inputFormat

The input consists of two lines:

  • The first line contains space-separated tokens representing the binary tree in level order. Use the token null for missing nodes.
  • The second line contains a single integer \(d\), representing the depth at which you need to sum the node values.

outputFormat

Output a single integer, which is the sum of all node values at depth \(d\). If there are no nodes at that level, output \(0\).

## sample
1 2 3 4 5 6 7
2
22