e-olymp
favorite We need a little bit of your help to keep things running, click on this banner to learn more
Problems

Tree Sum of leaves

Tree Sum of leaves

Given a binary tree. Find the sum of all its leaves.

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 SumLeaves that returns the sum of values of all its leaves.

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

Example

prb10112.gif

Function SumLeaves returns 31 = 5 + 9 + 17.

Time limit 1 second
Memory limit 128 MiB
Author Mykhailo Medvediev