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:
int sumOfLeftLeaves(TreeNode* root) {
int count=0;
if(root==NULL){
return NULL;
}
if(root->left!=NULL&&root->left->left==NULL&&root->left->right==NULL){
count+=root->left->val;
}
count+=sumOfLeftLeaves(root->left);
count+=sumOfLeftLeaves(root->right);
return count;
}
};