#K37797. Sum of Nodes at the Kth Level

    ID: 26056 Type: Default 1000ms 256MiB

Sum of Nodes at the Kth Level

Sum of Nodes at the Kth Level

You are given a binary tree represented by a list of parent node values. The tree has ( N ) nodes labeled from 1 to ( N ). The parent of the ( i )th node is given on the ( i )th position in the list, with the root node marked by a parent value of -1. Your task is to compute the sum of the node values at the ( k )th level of the tree. The level of the root node is 1. If there is no ( k )th level in the tree, output 0.

For example, consider the tree with ( N = 5 ) and parent values: -1, 1, 1, 2, 3. The tree structure is:

  • Level 1: Node 1 (root)
  • Level 2: Nodes 2 and 3
  • Level 3: Nodes 4 (child of 2) and 5 (child of 3)

If ( k = 3 ), the answer is ( 4 + 5 = 9 ).

inputFormat

Standard input (stdin) consists of three lines:

  1. An integer ( N ) representing the number of nodes in the tree.
  2. A line containing ( N ) space-separated integers representing the parent node of each node (nodes are numbered from 1 to ( N ); the root node has a parent of -1).
  3. An integer ( k ) representing the level at which you must compute the sum of node values.

outputFormat

Print a single integer to standard output (stdout), representing the sum of all node values at the ( k )th level. If the level does not exist, print 0.## sample

5
-1 1 1 2 3
3
9