原题
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)若节点为空,则为0;
(2)若左子节点为叶子节点,则加上其值,否则加上左子节点的所有左叶节点的和
(3)再加上右子节点的所有左叶子节点的和
代码
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root == NULL) return 0;
int ans = 0;
if(root->left != NULL){
if(root->left->left == NULL && root->left->right == NULL)
ans += root->left->val;
else
ans += sumOfLeftLeaves(root->left);
}
ans += sumOfLeftLeaves(root->right);
return ans;
}
};