# 404. 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.
``````

``````class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (!root || (!root->left && !root->right)) return 0;
int res = 0;
helper(root->left, true, res);
helper(root->right, false, res);
return res;
}
void helper(TreeNode* node, bool left, int& res) {
if (!node) return;
if (!node->left && !node->right && left) res += node->val;
helper(node->left, true, res);
helper(node->right, false, res);
}
};
``````

``````class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (!root) return 0;
if (root->left && !root->left->left && !root->left->right) {
return root->left->val + sumOfLeftLeaves(root->right);
}
return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
}
};
``````

``````class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (!root || (!root->left && !root->right)) return 0;
int res = 0;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode *t = q.front(); q.pop();
if (t->left && !t->left->left && !t->left->right) res += t->left->val;
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
return res;
}
};
``````

``````class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (!root || (!root->left && !root->right)) return 0;
int res = 0;
stack<TreeNode*> s;
s.push(root);
while (!s.empty()) {
TreeNode *t = s.top(); s.pop();
if (t->left && !t->left->left && !t->left->right) res += t->left->val;
if (t->left) s.push(t->left);
if (t->right) s.push(t->right);
}
return res;
}
};
``````

https://discuss.leetcode.com/topic/60467/3-line-c-solution

https://discuss.leetcode.com/topic/60381/java-solution-using-bfs

https://discuss.leetcode.com/topic/60415/java-solution-with-stack

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation