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 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;
}
};
网友评论