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.
方法1:
class Solution {
public:
int sum=0;
void DFS(TreeNode* root,int dir){
if(!root)return;
if(dir==1&&!root->left&&!root->right){
sum+=root->val;
}
DFS(root->left,1);
DFS(root->right,2);
}
int sumOfLeftLeaves(TreeNode* root) {
DFS(root,0);
return sum;
}
};
方法2:
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(!root)return 0;
else if(root->left&&!root->left->right&&!root->left->left) return root->left->val+sumOfLeftLeaves(root->right);
else return sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right);
}
};