Leetcode 404 Solution
This article provides solution to leetcode question 404 (sum-of-left-leaves)
Access this page by simply typing in "lcs 404" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/sum-of-left-leaves
Solution
/**
* 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, bool left)
{
if (root == NULL)
return 0;
if (root->left == NULL && root->right == NULL)
return left ? root->val : 0;
int sum = 0;
if (root->left)
sum += sumOfLeftLeaves(root->left, true);
if (root->right)
sum += sumOfLeftLeaves(root->right, false);
return sum;
}
int sumOfLeftLeaves(TreeNode* root) {
return sumOfLeftLeaves(root, false);
}
};