#K65252. Subtree Sums in a Tree
Subtree Sums in a Tree
Subtree Sums in a Tree
Given a tree with \(N\) nodes where each node has an assigned integer value, you are required to compute the sum of the values in the subtree of a given node for multiple queries. The subtree of a node includes the node itself and all its descendants when considering node 1 as the root.
You can solve this problem using a Depth-First Search (DFS) to traverse the tree and calculate the subtree sum for each node recursively. For each query, simply output the precomputed subtree sum.
inputFormat
The input is read from standard input in the following format:
- The first line contains a single integer \(N\) indicating the number of nodes in the tree.
- The second line contains \(N\) space-separated integers. The \(i\)th integer represents the value of node \(i\).
- The next \(N-1\) lines each contain two space-separated integers \(u\) and \(v\), representing an edge between nodes \(u\) and \(v\).
- The following line contains a single integer \(Q\) representing the number of queries.
- The next \(Q\) lines each contain a single integer representing the node for which the subtree sum is to be calculated.
outputFormat
For each query, output the sum of the node values in the subtree rooted at the queried node, each on a new line.
## sample5
1 2 3 4 5
1 2
1 3
2 4
2 5
3
1
2
4
15
11
4
</p>