Skip to main content

11. Maximum Depth of Binary Tree

easyAsked at SoFi

Return the height of a binary tree — SoFi uses this as a starter to verify candidates can write clean DFS, since loan-portfolio risk trees can grow deep across guarantor chains.

By Alex Chen, 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

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

Examples

Example 1

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

Example 2

Input
[1,null,2]
Output
2

Approaches

1. Brute force BFS

Level-order traversal incrementing a counter per level.

Time
O(n)
Space
O(n)
function maxDepth(root) {
  if (!root) return 0;
  let q = [root], d = 0;
  while (q.length) {
    q = q.flatMap(n => [n.left, n.right].filter(Boolean));
    d++;
  }
  return d;
}

Tradeoff:

2. Recursive DFS

Depth is 1 plus the max of depths of left and right subtrees, with base 0 for null.

Time
O(n)
Space
O(h)
function maxDepth(root) {
  if (!root) return 0;
  return 1 + Math.max(
    maxDepth(root.left),
    maxDepth(root.right)
  );
}

Tradeoff:

SoFi-specific tips

SoFi prefers recursive DFS for its readability — portfolio risk calculations propagate up the dependency tree the same way (each parent aggregates children's exposure).

Solve it now

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

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Maximum Depth of Binary Tree and other SoFi interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →