Problems

Maximum Depth of Binary Tree

easy
easy
binary-tree
recursion
depth-first-search

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 using null for missing children, e.g. [3, 9, 20, null, null, 15, 7])
  • Output: int — the maximum depth

Examples

  1. root = [3, 9, 20, null, null, 15, 7] returns 3.
  2. root = [] returns 0 (an empty tree has depth 0).
  3. root = [1] returns 1.

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

Input: root = [3,9,20,null,null,15,7]
Output: 3

Example 2 (empty tree)

Input: root = []
Output: 0

Example 3 (single node)

Input: root = [1]
Output: 1
🔒 5 hidden

Running will execute all 8 cases, including 5 hidden ones.