Sum of Left Leaves - Problem
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
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
โ Quadratic Growth
Space Complexity
O(n)
Need to store all leaf nodes and their parent relationships
โก 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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code