Sum of Left Leaves
Given the root
Example 1
Input: root = [3,9,20,null,null,15,7]
Output: 24
Explanation: There are two left leaves: 9 and 15. Their sum is 9 + 15 = 24.
Output: 24
Explanation: There are two left leaves: 9 and 15. Their sum is 9 + 15 = 24.
Example 2
Input: root = [1]
Output: 0
Explanation: The single node is the root (not a left leaf), so the sum is 0.
Output: 0
Explanation: The single node is the root (not a left leaf), so the sum is 0.
Constraints:
1 <= Number of nodes <= 1000-1000 <= Node.val <= 1000
Solution: Recursive DFS
The challenge is distinguishing a left leaf from a right leaf. We solve this by passing a boolean
flag isLeftisLeft == true
Algorithm:
- Call the helper with the root, marking it as
.isLeft = false - If the node is null, return 0.
- If the node is a leaf and
is true, return the node's value.isLeft - Otherwise, recurse: pass
for the left child,true for the right child.false
Java
public int sumOfLeftLeaves(TreeNode root) {
return dfs(root, false);
}
private int dfs(TreeNode node, boolean isLeft) {
if (node == null) return 0;
// leaf node that was reached as a left child
if (node.left == null && node.right == null) {
return isLeft ? node.val : 0;
}
return dfs(node.left, true) // left child → isLeft = true
+ dfs(node.right, false); // right child → isLeft = false
}
Trace through Example 1: root = [3,9,20,null,null,15,7]
| Node | isLeft | Is Leaf? | Contribution |
|---|---|---|---|
| 3 | false | No | recurse |
| 9 | true | Yes | +9 |
| 20 | false | No | recurse |
| 15 | true | Yes | +15 |
| 7 | false | Yes | +0 |
Total = 9 + 15 = 24.
Complexity Analysis
- Time: O(n). Every node is visited exactly once.
- Space: O(h). Recursion stack depth equals the tree height h (O(log n) for balanced trees, O(n) worst case for skewed trees).