leetcode Sum of Left Leaves

Description

Find the sum of all left leaves in a given binary tree.

Example:

1
2
3
4
5
6
7
    3
/ \
9 20
/ \
15 7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

The original problem is here.

My Solution

I solve this problem in C++, as below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int res = 0;
int sumOfLeftLeaves(TreeNode* root) {
if (root == NULL)
return 0;
if (isLeaf(root))
return 0;
sum(root);
return res;

}
void sum(TreeNode* node) {
if (node == NULL)
return;
if (isLeaf(node->left))
res += node->left->val;
else{
sum(node->left);
}
sum(node->right);
}

bool isLeaf(TreeNode* node) {
if (node == NULL)
return false;
if(node->left == NULL && node->right == NULL)
return true;
return false;
}
};

Note

To solve the problem, traverse the tree recursively, if the node is left leaf add the value to the result.