Skip to main content

11. Maximum Depth of Binary Tree

easyAsked at Squarespace

Return the longest root-to-leaf path length of a binary tree; Squarespace uses it to check whether you reach for a clean recursion or unnecessary state.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given the root of a binary tree, return its maximum depth, defined as the number of nodes along the longest path from the root down to the farthest leaf.

Constraints

  • 0 <= number of nodes <= 10^4
  • -100 <= Node.val <= 100

Examples

Example 1

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

Example 2

Input
root=[]
Output
0

Approaches

1. BFS level count

Walk level by level with a queue and count how many levels you traversed.

Time
O(n)
Space
O(w)
if(!root) return 0;
let q=[root], d=0;
while(q.length){ const nx=[]; for(const n of q){ if(n.left) nx.push(n.left); if(n.right) nx.push(n.right);} q=nx; d++; }
return d;

Tradeoff:

2. Recursive max

Return 1 plus the max depth of either child. Base case at null returns 0.

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

Tradeoff:

Squarespace-specific tips

Squarespace likes a brief callout that depth-bounded recursion matters when rendering nested template sections so a deep editor tree does not blow the stack.

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 Squarespace interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →