题目描述:
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.
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
int sum=0;
if(root==NULL) return sum;
if(root->left!=NULL) visit_leaves(root->left,sum,true);
if(root->right!=NULL) visit_leaves(root->right,sum,false);
return sum;
}
void visit_leaves(TreeNode* root, int& sum, bool isLeft)
{
if(root==NULL) return;
if(isLeft&&root->left==NULL&&root->right==NULL) sum+=root->val;
if(root->left!=NULL) visit_leaves(root->left,sum,true);
if(root->right!=NULL) visit_leaves(root->right,sum,false);
}
};