104/670

104. Maximum Depth of Binary Tree

Easy

Your function receives the root of a binary tree (possibly empty; each node exposes val, left, and right). Compute the tree's maximum depth: the number of nodes on the longest path that starts at the root and walks downward to a leaf.

A single lonely node has depth 1; an empty tree has depth 0. Return the depth as an integer.

The values stored in the nodes are irrelevant here — only the shape of the tree matters.

The longest root-to-leaf walkThe highlighted walk 3 → 20 → 15 touches three nodes, so the maximum depth is 3. The branch through 9 stops after two.
depth 1depth 2depth 33920157

Example 1:

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

Output: 3

Explanation: The longest downward walks are 3 → 20 → 15 and 3 → 20 → 7, each touching three nodes.

Example 2:

Input: root = [1, null, 2]

Output: 2

Explanation: The root has only a right child, so the deepest path is 1 → 2: two nodes.

Constraints:

  • 0 ≤ number of nodes ≤ 1000
  • -100 ≤ Node.val ≤ 100

Hints:

Think one node at a time: if you already knew how deep each of the two subtrees goes, how deep does the tree rooted here go?

depth(node) = 1 + max(depth(node.left), depth(node.right)), with depth(empty) = 0. Alternatively, run a level-order sweep and count how many rounds it takes to drain the queue.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

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

Expected output: 3