Given the root of a binary tree, return its maximum depth: the number of nodes along the longest path from the root down to the farthest leaf. This is the first problem to use the judge's typed TreeNode support: root is a real tree built from the JSON test fixture, not a flat array — your function must walk .left/.right pointers like a genuine LeetCode submission.
Input / output
- Input:
root: TreeNode(JSON test fixture is a LeetCode-style level-order array usingnullfor missing children, e.g.[3, 9, 20, null, null, 15, 7]) - Output:
int— the maximum depth
Examples
root = [3, 9, 20, null, null, 15, 7]returns3.root = []returns0(an empty tree has depth 0).root = [1]returns1.
Constraints
0 <= number of nodes <= 10,000-100 <= node value <= 100
Follow-up Can you solve it both recursively (depth-first) and iteratively with an explicit stack or a level-by-level breadth-first traversal, and explain when you'd prefer one over the other?
Note
Java, Go, and Rust starters are shown for reference only on this problem right now — the remote judge for those languages doesn't yet support the TreeNode structure. Use Python or JavaScript to run and submit.
Examples
Example 1
Example 2 (empty tree)
Example 3 (single node)
Running will execute all 8 cases, including 5 hidden ones.