You are given the root of a binary tree. Call a node a leaf when both of its child slots are empty, and a left leaf when it is such a node sitting in its parent's left slot.
Return the sum of the values of all left leaves. If the tree has none, return 0.
Example 1
Input: root = [6, 3, 9, 1, 4, 2] Output: 3 Why: the left leaves are 1 and 2; the leaf 4 is a right child
2 more examples and the constraints
Example 2
Input: root = [7] Output: 0 Why: the root is a leaf, but it is nobody's left child
Example 3
Input: root = [2, null, 5, 4] Output: 4 Why: 4 is the left child of 5, and it has no children
Constraints
- The tree has between 1 and 1,000 nodes
- −1,000 ≤ each node value ≤ 1,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- BFS, check each left childO(n)
- Recursive DFS with a side flagO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a tree of 1,000 nodes | Verdict |
|---|---|---|---|
| BFS, check each left child | O(n) | Passes; holds a whole level | |
| Recursive DFS with a side flag | O(n) | Best; shortest to write |
n = number of nodes, w = widest level, h = height. Both visit every node once.
Edge cases to test
- A single node. [7] is a leaf with no parent, so the sum is 0.
- Right leaves only. [1, null, 2, null, 3] has one leaf, on the right: the sum is 0.
- Left child with children. In [1, 2, null, 3], node 2 is on the left but is not a leaf. Its own left child 3 is the left leaf.
- Left leaves under right children. In [2, null, 5, 4], the leaf 4 is the left child of 5. It counts, so keep searching right subtrees.
- Negative values. The sum can be negative; do not start from or compare against a sentinel.
Common mistakes
- Counting the root when the tree has one node.
- Adding every left child, even ones that still have children.
- Skipping the right subtree because only left leaves count.
How to talk through it
- 1Clarify. Does the root count if it is the only node? Can values be negative?
- 2Name what a node is missing. A node does not know if it is a left child, so the parent must tell it, or check for it.
- 3Pick the traversal. Any order works. Recursion with a side flag is the shortest; BFS avoids deep recursion.
- 4Give the cost. O(n) time; O(h) stack for DFS, O(w) queue for BFS.
- 5Test out loud. Run a single node, a right-only chain, and a left leaf under a right child.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?