You get root, the top node of a binary tree. A leaf is any node without children. Among all paths that start at the root and go straight down to a leaf, find the shortest one.
Return how many nodes that shortest path has. An empty tree gives 0, and a tree that is only a root gives 1.
Example 1
Input: root = [8, 3, 6, null, 5, 2, null, 4, 1] Output: 3 Why: 8 → 6 → 2 reaches the leaf 2 in three nodes
2 more examples and the constraints
Example 2
Input: root = [1, null, 7, null, 3] Output: 3 Why: a chain; the only leaf is 3, at the bottom
Example 3
Input: root = [] Output: 0 Why: no nodes, so no path
Constraints
- 0 ≤ number of nodes ≤ 100,000
- −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.
- Recursive DFSO(n)
- Level by level (BFS)O(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 nodes | Verdict |
|---|---|---|---|
| Recursive DFS | O(n) | Short; always reads every node | |
| Level by level (BFS) | O(n) | Best; stops at the first leaf |
n = number of nodes, h = height, w = widest level. Both are O(n) in the worst case; BFS often stops much sooner.
Edge cases to test
- Empty tree. [] must give 0. Check for a missing root first.
- Only a root. [42] gives 1: the root is itself a leaf.
- Root with one child. [1, 2] gives 2, not 1. The root has a child, so it is not a leaf.
- A long chain. Every node has one child; the only leaf is at the bottom, so the answer is the node count.
Common mistakes
- Copying max depth and swapping max for min, so a node with one child returns 1 + 0 and the empty side wins.
- Treating any node with a missing child as a leaf; a leaf needs both children missing.
- In BFS, checking for a leaf only after the whole level is queued, instead of returning on the first one.
How to talk through it
- 1Clarify. Is depth counted in nodes? What does an empty tree return? Is a node with one child a leaf?
- 2Start from max depth. Point out that swapping max for min breaks on a node with one child, and fix that case.
- 3Name the cost. The recursion reads every node and goes as deep as the tree. It cannot stop early.
- 4Switch to BFS. Levels come out nearest first, so the first leaf popped gives the answer. Return there.
- 5Test out loud. Run an empty tree, a lone root, a root with one child and a chain.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?