404. Sum of Left Leaves*
https://leetcode.com/problems/sum-of-left-leaves/
题目描述
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.
C++ 实现 1
注意是求所有 left 叶子节点的值的和. 如果使用层序遍历.
/**
* 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) {
if (!root) return 0;
int sum = 0;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
auto r = q.front();
q.pop();
if (r->left) {
if (!r->left->left && !r->left->right) sum += r->left->val;
q.push(r->left);
}
if (r->right) q.push(r->right);
}
return sum;
}
};
C++ 实现 2
使用递归来做.
/**
* 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) {
if (!root || (!root->left && !root->right))
return 0;
if (root->left && (!root->left->left && !root->left->right))
return root->left->val + sumOfLeftLeaves(root->right);
else
return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
}
};