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.
思路
遍歷整棵樹宁仔,注意判定條件不是當前節(jié)點是不是葉子,而是當前節(jié)點有沒有左葉子結(jié)點峦睡,有則計入總和翎苫,沒有則在左右子樹遞歸遍歷。
/**
* 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 res=0;
if(!root || (!root->left && !root->right)) return 0;
if(root->left && (!root->left->left && !root->left->right)) res+=root->left->val;
res+=sumOfLeftLeaves(root->left);
res+=sumOfLeftLeaves(root->right);
return res;
}
};