e-olymp
Competitions

class Tree

Tree Sum of elements

Binary tree is given. Find the sum of values in all its nodes.

Definition of a tree:

// Java
class TreeNode
{
public:
  int val;
  TreeNode left;
  TreeNode right;
  TreeNode(int x) {
    val = x;
    left = NULL; 
    right = NULL;
};
// C++
class TreeNode
{
public:
  int val;
  TreeNode *left;
  TreeNode *right;
  TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

Implement function Sum that returns the sum of values of all nodes in the tree.

// Java
int Sum(TreeNode tree)
// C++
int Sum(TreeNode *tree)

Example

prb10057.gif

Function Sum returns value 45 - the sum 1 + 2 + 3 + 4 + 9 + 10 + 16 = 45.

Time limit 1 second
Memory limit 128 MiB
Author Mykhailo Medvediev