Tree Sum of leaves#10113

Tree Sum of leaves

1 second
128 megabytes
Very easy

Given a binary tree, find the sum of all its leaves.

A leaf is a node that does not have any children.

The binary tree is defined as follows:

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

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

Examples

prb10112.gif

The function SumLeaves returns = + + .