Sum of Left Leaves
The key idea
A node only knows it is a left leaf if its parent tells it. So pass an
isLeft flag down to each child, and add a node's value only when it has no children AND it arrived as a left child.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.
Constraints
- The number of nodes in the tree is in the range
[1, 1000]. -1000 <= Node.val <= 1000
Examples
Input: root = [3,9,20,null,null,15,7]
Output: 24
Input: root = [1]
Output: 0
Complexity
Time: O(n) Space: O(h)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Tree / Recursion problems
- Balanced Binary TreeEASY
- Binary Tree CamerasHARD
- Binary Tree Inorder TraversalEASY
- Binary Tree Maximum Path SumHARD
- Binary Tree PathsEASY
- Binary Tree Postorder TraversalEASY
- Binary Tree Preorder TraversalEASY
- House Robber IIIMEDIUM
- Construct Binary Tree from Inorder and Postorder TraversalMEDIUM
- Construct Binary Tree from Preorder and Inorder TraversalMEDIUM
- Convert BST to Greater TreeMEDIUM
- Count Complete Tree NodesEASY