404. Sum of Left Leaves LeetCode Solution

In this guide, you will get 404. Sum of Left Leaves LeetCode Solution with the best time and space complexity. The solution to Sum of Left Leaves problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Sum of Left Leaves solution in C++
  4. Sum of Left Leaves solution in Java
  5. Sum of Left Leaves solution in Python
  6. Additional Resources
404. Sum of Left Leaves LeetCode Solution image

Problem Statement of Sum of Left Leaves

Given the root of a binary tree, return the sum of all left leaves.
A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: 24
Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.

Example 2:

Input: root = [1]
Output: 0

Constraints:

The number of nodes in the tree is in the range [1, 1000].
-1000 <= Node.val <= 1000

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(h)

404. Sum of Left Leaves LeetCode Solution in C++

class Solution {
 public:
  int sumOfLeftLeaves(TreeNode* root) {
    if (root == nullptr)
      return 0;

    int ans = 0;

    if (root->left) {
      if (root->left->left == nullptr && root->left->right == nullptr)
        ans += root->left->val;
      else
        ans += sumOfLeftLeaves(root->left);
    }
    ans += sumOfLeftLeaves(root->right);

    return ans;
  }
};
/* code provided by PROGIEZ */

404. Sum of Left Leaves LeetCode Solution in Java

class Solution {
  public int sumOfLeftLeaves(TreeNode root) {
    if (root == null)
      return 0;

    int ans = 0;

    if (root.left != null) {
      if (root.left.left == null && root.left.right == null)
        ans += root.left.val;
      else
        ans += sumOfLeftLeaves(root.left);
    }
    ans += sumOfLeftLeaves(root.right);

    return ans;
  }
}
// code provided by PROGIEZ

404. Sum of Left Leaves LeetCode Solution in Python

class Solution:
  def sumOfLeftLeaves(self, root: TreeNode | None) -> int:
    if not root:
      return 0

    ans = 0

    if root.left:
      if not root.left.left and not root.left.right:
        ans += root.left.val
      else:
        ans += self.sumOfLeftLeaves(root.left)
    ans += self.sumOfLeftLeaves(root.right)

    return ans
# code by PROGIEZ

Additional Resources

See also  51. N-Queens LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.