Given the
Output: 24
Explanation: There are two left leaves: 9 and 15. Their sum is 9 + 15 = 24.
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
Contents
Solution — Recursive DFS Complexity Analysis
The challenge is distinguishing a left leaf from a right leaf. We solve this by passing a boolean
flag
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
isLeft is true, return the node's value. - Otherwise, recurse: pass
true for the left child,false for the right child.
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.
- 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).