LeetCode 404: Sum of Left Leaves Solution

Master LeetCode problem 404 (Sum of Left Leaves), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation:

To solve this problem, we can perform a depth-first traversal of the binary tree. While traversing, we keep track of whether a node is a left child and also whether it is a leaf node. If a node is a left child and a leaf node, we add its value to the sum.

Algorithm:

  1. Initialize a variable sum to store the sum of left leaves and start a depth-first traversal of the tree.
  2. At each node, check if it is a leaf node and a left child. If it is, add its value to the sum.
  3. Recursively traverse the left and right subtrees, passing the information about whether the current node is a left child or not.
  4. Return the sum calculated during the traversal.

Time Complexity: O(n) - where n is the number of nodes in the binary tree. Space Complexity: O(h) - where h is the height of the binary tree (recursion stack space).

:

Solution Code

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) return 0;
        
        int sum = 0;
        if (root.left != null && root.left.left == null && root.left.right == null) {
            sum += root.left.val;
        }
        
        sum += sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
        
        return sum;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 404 (Sum of Left Leaves)?

This page provides optimized solutions for LeetCode problem 404 (Sum of Left Leaves) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 404 (Sum of Left Leaves)?

The time complexity for LeetCode 404 (Sum of Left Leaves) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 404 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 404 in Java, C++, or Python.

Back to LeetCode Solutions