Skip to main content

104. Maximum Depth of Binary Tree

easy

Compute the maximum depth (root-to-leaf height) of a binary tree. The canonical recursion warm-up — every tree problem builds on this pattern.

By Sam K., Founder, InterviewChamp.AI · Last verified

Problem

Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Constraints

  • The number of nodes in the tree is in the range [0, 10^4].
  • -100 <= Node.val <= 100

Examples

Example 1

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

Example 2

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

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

Recursion: depth(node) = 1 + max(depth(node.left), depth(node.right)).

Hint 2

Base case: depth(null) = 0.

Hint 3

Iterative BFS works too — count levels until the queue is empty.

Solution approach

Reveal approach

Recursive DFS. If the node is null, return 0. Otherwise return 1 + max(depth(node.left), depth(node.right)). Each node contributes 1 to its own depth and lifts the maximum of its subtrees' depths. O(n) time visiting each node once; O(h) space for the recursion stack (h = tree height, up to n in the worst case of a skewed tree). Iterative alternative: BFS with a queue, incrementing a level counter per processed level — also O(n) time with O(width) space.

Complexity

Time
O(n)
Space
O(h)

Related patterns

  • dfs
  • bfs
  • recursion

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

  • Amazon
  • Microsoft

More Trees practice problems

See all Trees problems →