404. Sum of Left Leaves
1. Description
Find the sum of all left leaves in a given binary tree.
2. Solutions
My Accepted Solution
n is the number of nodes in i_root
Time complexity: O(nk)
Space complexity: O(1)
// we could also use breadth-first search(iteration or level search)
class Solution
{
private:
int result = 0;
void sumOfLeftLeaves(TreeNode *i_root, int isLeftChild)
{
if(!i_root->left && !i_root->right) result += i_root->val * isLeftChild;
if(i_root->left) sumOfLeftLeaves(i_root->left, 1);
if(i_root->right) sumOfLeftLeaves(i_root->right, 0);
}
public:
// int sumOfLeftLeaves(TreeNode* root)
int sumOfLeftLeaves(TreeNode *i_root)
{
if(!i_root) return result;
sumOfLeftLeaves(i_root, 0);
return result;
}
};