Sum of Left Leaves
Easy · Trees · Tree · Depth-First Search · Breadth-First Search · Binary Tree
Problem
Given the root of a binary tree, return the sum of all left leaves.
A left leaf is a node with no children that is the left child of its parent. A tree that is only a root has no left leaves.
Examples
Input: root = [1,2,3,4,5,6] Output: 10
The left leaves are 4 (child of 2) and 6 (child of 3); 5 is a right leaf.
Input: root = [9] Output: 0
The root is nobody's left child.
Input: root = [3,9,20,null,null,15,7] Output: 24
9 is a left leaf under the root and 15 a left leaf under 20: 24.
Constraints
- The number of nodes is in the range [1, 1000]
- -1000 <= Node.val <= 1000
Approaches
- List every leaf, then ask its parent — time O(n), space O(n)
Follow-up
The decision is made at the parent because "left" is a property of the edge, not of the node. The use cases drop the leaf condition (every left child) and report the left and right leaf sums together, which needs the side carried down with each node.
Related problems
Start free on Cariara · Coding problems · System design studio