> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Sum of Left Leaves Python Solution with Tests

> Tested Python solution for LeetCode 404 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 404, [Easy](/catalog/easy). Topics: [Tree](/catalog/topics/tree), [Depth-First Search](/catalog/topics/depth-first-search), [Breadth-First Search](/catalog/topics/breadth-first-search), [Binary Tree](/catalog/topics/binary-tree). [View on LeetCode](https://leetcode.com/problems/sum-of-left-leaves/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 404   # by problem number
lcpy gen -s sum_of_left_leaves   # by problem name
```

## Problem

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.

### Examples

![Example 1](https://assets.leetcode.com/uploads/2021/04/08/leftsum-tree.jpg)

```
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.
```

```
Input: root = [1]
Output: 0
```

### Constraints

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

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/sum_of_left_leaves/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/sum_of_left_leaves/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from leetcode_py import TreeNode


class Solution:
    # Time: O(n)
    # Space: O(h)
    def sum_of_left_leaves(self, root: TreeNode[int] | None) -> int:
        if root is None:
            return 0
        if root.left is not None and root.left.left is None and root.left.right is None:
            return root.left.val + self.sum_of_left_leaves(root.right)
        return self.sum_of_left_leaves(root.left) + self.sum_of_left_leaves(root.right)
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(h) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.