#K69182. Sum of Node Values at a Given Depth
Sum of Node Values at a Given Depth
Sum of Node Values at a Given Depth
You are given a binary tree represented in level order as an array. In this representation, each non-null node is given as an integer and a -1
is used to indicate that a node is absent (i.e. a null node). The tree is constructed in level order: the first element is the root, and for each non-null node, its left and right children (if available) are taken from the array in order. If a node is -1
, it is considered null and its children are treated as absent (but placeholders of -1
may still be present in the array to maintain the structure).
Your task is to compute the sum of values of the nodes at a given depth. The depth is defined such that the root is at depth \(0\). If the given depth is beyond the depth of the tree or if the tree is empty, output 0
.
Note: Only non-null nodes (i.e. nodes with values not equal to -1
) contribute to the sum.
inputFormat
The input is read from standard input (stdin) and consists of two lines:
- The first line contains the level order traversal of the tree as space-separated integers. An empty line indicates an empty tree.
- The second line contains a single integer representing the target depth.
outputFormat
Output a single integer which is the sum of all node values (ignoring -1
which indicate null nodes) at the specified depth. If there are no nodes at that depth, output 0
.
1 2 3 4 5 -1 -1 -1 -1 6 7
2
9