Given the root of a binary tree, your task is to find and return the sum of all left leaves.

A leaf is a node that has no children (both left and right children are null). A left leaf is specifically a leaf node that is the left child of its parent.

Important: Not all leaves count! Only those leaves that are left children of their parent nodes should be included in the sum.

Example: In a tree where node 5 has a left child 9 (which is a leaf) and a right child 1, only the value 9 would contribute to our sum since it's a left leaf.

Input & Output

example_1.py โ€” Basic Tree
$ Input: [3,9,20,null,null,15,7]
โ€บ Output: 24
๐Ÿ’ก Note: The tree has two leaves: 9 (left child of 3) and 7 (right child of 20). Only node 9 is a left leaf, so the sum is 9. Wait, let me recalculate... Actually, node 15 is a left child of 20 and is a leaf, so the sum should include 15. The sum is 24.
example_2.py โ€” Single Node
$ Input: [1]
โ€บ Output: 0
๐Ÿ’ก Note: A single node tree has no left leaves since the root cannot be a left child of any node.
example_3.py โ€” Only Right Children
$ Input: [1,null,2,null,3,null,4]
โ€บ Output: 0
๐Ÿ’ก Note: This tree has only right children, so there are no left leaves. The sum is 0.

Visualization

Tap to expand
3root9left20right15LEFT LEAF!7right leafAlgorithm Steps:1. Start DFS from root (not left child)2. Visit left children (mark as left child)3. Visit right children (mark as right child)4. If leaf AND left child โ†’ add to sumResult: Sum = 15 (only node 15 qualifies)Key Insight:Track parent-child relationshipduring single tree traversalO(n) time, O(h) space
Understanding the Visualization
1
Start at Root
Begin the journey at the root node, marking it as 'not a left child'
2
Explore Left Branch
Move to left child and mark it as 'left child', continue recursively
3
Check Leaf Status
When reaching a node with no children, check if it's marked as 'left child'
4
Sum Left Leaves
Add values of nodes that are both leaves AND left children
Key Takeaway
๐ŸŽฏ Key Insight: Use DFS with a boolean flag to identify left leaves in a single traversal - when a node is both a leaf AND came from a left path, include it in the sum!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยฒ)

Multiple passes through the tree, where each pass visits O(n) nodes

n
2n
โš  Quadratic Growth
Space Complexity
O(n)

Need to store all leaf nodes and their parent relationships

n
2n
โšก Linearithmic Space

Constraints

  • The number of nodes in the tree is in the range [1, 1000]
  • Node values are in the range [-1000, 1000]
  • A leaf node has both left and right children as null
Asked in
Facebook 15 Amazon 12 Google 8 Microsoft 6
89.6K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen