InterviewPrepKit

Home / Coding / Trees

Maximum Depth of Binary Tree

easy Original ↗
Solving tips
  • Recognize the self-similar recursion: depth(node) = 1 + max(depth(left), depth(right)) with depth(None) = 0 — a one-line DFS, O(n) time, O(h) space.
  • Know an iterative form for the 'no recursion' follow-up: BFS counting levels (snapshot len(queue) per round) or a stack of (node, depth) pairs.
  • Pitfall: this counts NODES (single node depth 1, empty tree 0), unlike the height-in-edges convention — state which you use.
  • Pitfall: a skewed 10^4-node tree can exceed Python's default recursion limit, so mention the iterative variant; and in BFS remember the len(queue) snapshot or it becomes node counting.

Problem

Given the root of a binary tree, return its maximum depth: the number of nodes on the longest path from the root down to any leaf. An empty tree has depth 0; a single node has depth 1.

Examples

Example 1

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

        3
       / \
      9  20
        /  \
       15   7

Output: 3

The longest root-to-leaf paths (3→20→15, 3→20→7) contain 3 nodes.

Example 2

Input:  root = [1,null,2]
Output: 2

The only path is 1 → 2.

Example 3

Input:  root = []
Output: 0

No nodes, depth 0.

Constraints

  • The number of nodes is in [0, 10^4] — a single O(n) traversal is expected.
  • -100 <= Node.val <= 100 — values never matter; only shape does.

Think about it first

Hint 1 If someone handed you the depths of the left subtree and the right subtree, how would you get the depth of the whole tree?
Hint 2 `depth(node) = 1 + max(depth(node.left), depth(node.right))`, with `depth(None) = 0`. That's a complete algorithm — write it.
Hint 3 Two classic non-recursive versions: BFS counting how many levels you peel off, or DFS with a stack of `(node, depth)` pairs. Know one for the "no recursion" follow-up.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.