You are given the root of an n-ary tree: each node holds a value and a list of any number of children. Return its maximum depth, the count of nodes on the longest path that starts at the root and goes down to a leaf.
An empty tree has depth 0, and a tree with just a root has depth 1. In the examples the tree is written in level order: the root, then a null, then each node’s children as a group, with a null closing every group.
Example 1
Input: root = [2, null, 8, 5, 1, null, 4, null, null, 7] Output: 3 Why: 2 → 8 → 4 (or 2 → 1 → 7) passes three nodes
2 more examples and the constraints
Example 2
Input: root = [] Output: 0 Why: an empty tree has no nodes on any path
Example 3
Input: root = [6, null, 3, null, 9, null, 1] Output: 4 Why: each node has one child: 6 → 3 → 9 → 1
Constraints
- 0 ≤ number of nodes ≤ 10,000
- The depth of the tree is at most 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 BFSO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 nodes | Verdict |
|---|---|---|---|
| Recursive DFS | O(n) | Shortest code; uses the call stack | |
| Level-by-level BFS | O(n) | Best; no recursion at all |
n = nodes, h = height of the tree, w = widest level.
Edge cases to test
- Empty tree. Return 0, not 1: there is no root to count.
- A leaf root. One node and no children: depth 1.
maxover no children needs a default of 0. - A long chain. 1,000 nodes in a line: the recursion goes 1,000 calls deep, which is fine; BFS uses no stack at all.
- A very wide root. One root with 9,999 leaf children: depth 2, and the BFS queue briefly holds all 9,999 leaves.
Common mistakes
- Calling
maxon an empty list of child depths in Python without a default. - Counting edges instead of nodes, which gives one less than the answer.
- In BFS, popping until the queue is empty in one round, which merges all levels into one.
How to talk through it
- 1Clarify. Is depth counted in nodes or edges? What does an empty tree return? How deep can the tree get?
- 2Define it recursively. Depth is 1 plus the deepest child, 0 for an empty tree.
- 3Offer the iterative version. Count BFS levels with a queue; useful when the tree might be deeper than the call stack allows.
- 4State the cost. O(n) time either way; O(h) stack for DFS, O(w) queue for BFS.
- 5Test out loud. Run the empty tree, a single node and Example 1.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?