Sum of Left Leaves — LeetCode 404 Python Solution
EasyTreeDepth-First SearchBreadth-First SearchBinary Tree
- Problem
- #404
- Pattern
- Tree Traversal
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given the root of a binary tree, return the sum of all left leaves. A leaf is a node with no children.
Example
- 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.
Python solution
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
ans = self.sumOfLeftLeaves(root.right)
if root.left:
if root.left.left == root.left.right:
ans += root.left.val
else:
ans += self.sumOfLeftLeaves(root.left)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the number of nodes in the binary tree auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 404. Sum of Left Leaves is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 404. Sum of Left Leaves?
- LeetCode 404. Sum of Left Leaves is rated Easy on LeetCode.
- What is the time complexity of LeetCode 404. Sum of Left Leaves?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 404. Sum of Left Leaves?
- The Python solution on this page uses O(n), where n is the number of nodes in the binary tree auxiliary space.
- What topics does LeetCode 404. Sum of Left Leaves cover?
- LeetCode 404. Sum of Left Leaves is tagged Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.