#K41312. Sum of Node Values at Given Depths
Sum of Node Values at Given Depths
Sum of Node Values at Given Depths
You are given a binary tree represented as a list of nodes. Each node is described by a triplet of integers: (value, left, right)
. The value
represents the node's value, and left
and right
are the indices of its left and right children respectively (with 0
indicating the absence of a child). The nodes are provided in level order, where the first node is the root (at depth \(0\)).
Your task is to compute the sum of the node values at a given depth \(d\) (using 0-indexing for depth). You will be provided with multiple test cases. For each test case, you need to output the sum for that test case on a separate line.
Note: The tree is constructed using the given list. The children indices refer to the 1-indexed positions in the list.
inputFormat
The input is read from standard input and has the following format:
- The first line contains an integer \(T\), the number of test cases.
- Each test case begins with a line containing two integers \(d\) and \(n\):
- \(d\): the target depth (0-indexed).
- \(n\): the number of nodes in the tree.
- This is followed by \(n\) lines, each containing three integers:
value left right
. Here,left
andright
are indices (1-indexed) of the left and right children respectively, with a value of 0 indicating that the child does not exist.
outputFormat
For each test case, output a single integer representing the sum of the node values at depth \(d\) on a separate line. The output is written to standard output.
## sample5
2 5
1 2 3
2 4 5
3 0 0
4 0 0
5 0 0
1 3
6 2 3
2 0 0
3 0 0
3 3
6 2 3
2 0 0
3 0 0
0 1
10 0 0
1 5
5 2 3
3 4 0
8 0 5
1 0 0
7 0 0
9
5
0
10
11
</p>