#K10231. Sum of Binary Tree Nodes

    ID: 23201 Type: Default 1000ms 256MiB

Sum of Binary Tree Nodes

Sum of Binary Tree Nodes

You are given a binary tree with integer values. The tree is represented in a specific format as follows:

  • The first line contains a single integer \(N\) which represents the number of nodes in the tree. If \(N=0\), the tree is empty.
  • Each of the next \(N\) lines contains three integers: value, left, and right. Here, value is the value of the node, and left and right are the indices of the left and right children of the node respectively. A value of -1 for left or right indicates that the corresponding child does not exist.
  • The node with index 0 is always the root of the tree.

Your task is to compute the sum of all node values in the binary tree and output the result to stdout. Formally, if the binary tree is represented as \(T = (V, E)\) with node values \(v_i\), you need to calculate the sum \(S = \sum_{i \in V} v_i\).

inputFormat

The input is read from standard input (stdin) as follows:

The first line contains an integer (N) which denotes the number of nodes in the tree. If (N = 0), the tree is empty.

Each of the next (N) lines contains three space-separated integers: value, left, and right. The integers left and right represent the indices of the left and right child respectively, or -1 if the child does not exist.

outputFormat

Output a single integer to standard output (stdout), which is the sum of all the node values in the binary tree.## sample

5
10 1 2
5 3 4
15 -1 -1
2 -1 -1
7 -1 -1
39