#K56117. Children Sum Query on Binary Tree
Children Sum Query on Binary Tree
Children Sum Query on Binary Tree
You are given a binary tree where each node is described by a triplet: the node's value, its left child's value, and its right child's value. A value of -1
represents a missing child. After constructing the tree, you will be given several queries. For each query, output the sum of the left and right children's values of the specified node. If a child does not exist, consider its value as 0.
Formally, for a node with value v, if its left child has value L and its right child has value R, output the sum \( S = L + R \). If a child is absent, its contribution to the sum is 0.
The input and output are read from standard input and written to standard output respectively.
inputFormat
The first line contains an integer \( n \) representing the number of nodes in the tree.
The following \( n \) lines each contain three space-separated integers: value left right
. Here, value
is the node's value, and left
and right
are the values of its left and right children respectively. A value of -1
indicates that the corresponding child is missing.
The next line contains an integer \( q \) representing the number of queries. Each of the following \( q \) lines contains a single integer representing the query node's value.
outputFormat
For each query, output a single integer: the sum of the left and right children's values of the queried node.
Each result should be printed on a new line.
## sample3
1 2 3
2 -1 -1
3 -1 -1
3
1
2
3
5
0
0
</p>