Sum of Left Leaves in Binary tree – LeetCode Solution [Easy]

Problem

Given the root of a binary tree, return the sum of all left leaves.

LeetCode Problem Link

Input

root of a binary tree

Output

sum of all left leaves

Constraints
  • 1 <= Number of Nodes in the Tree ≤ 1000
  • -1000 <= Value of Nodes ≤ 1000
Sample Input
Binary Tree
root = [5, 3, 7, 2, 6]
Sample Output
2
Solution

Approach: Recursion

class Solution {
public:
    
    void solve (TreeNode* root, int &sum) {
        if (root == NULL) {
            return;
        }
        
        if (root->left != NULL) {
            if (root->left->left == NULL && root->left->right == NULL) {
                sum += root->left->val;
            }
        }
        
        solve (root->left, sum);
        solve (root->right, sum);
    }
    
    int sumOfLeftLeaves (TreeNode* root) {
        int sum = 0;
        solve(root, sum);
        return sum;
    }
};

Time complexity: O(n), n is the number of leaves in the binary tree

Leave a Reply

Your email address will not be published. Required fields are marked *