Find the sum of all left leaves in a given binary tree.
Example:
3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
/**
* 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:
void getLeftSum(TreeNode* root,int flag,int &sum)
{
if(root->left != NULL)
{
flag = 1;
getLeftSum(root->left,flag,sum);
}
if(root->right != NULL)
{
flag = 0;
getLeftSum(root->right,flag,sum);
}
if(root->left == NULL && root->right == NULL)
{
if(flag == 1)
sum += root->val;
}
return;
}
int sumOfLeftLeaves(TreeNode* root) {
if(root == NULL) return 0;
int flag = 0;
int sum = 0;
getLeftSum(root,flag,sum);
return sum;
}
};