📖 5 min read
Last updated on

Maximum Depth of Binary Tree — Coding Interview Walkthrough


You’re in a phone screen and the interviewer pulls up Maximum Depth of Binary Tree. It looks trivial — three lines of recursion. But they’re not testing whether you can write those three lines. They’re watching whether you can explain why those three lines are correct, articulate the base case without hesitation, and pivot to an iterative BFS when they ask about stack overflow on skewed trees.


The Problem

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

Example

Input

    3
   / \
  9  20
    /  \
   15   7

Output 3

The longest path is 3 → 20 → 15 (or 3 → 20 → 7), which has 3 nodes.

Already comfortable with the solution? Practice it in a mock interview →


What Interviewers Are Actually Testing

SkillWhat Interviewers Observe
Recursive decompositionCan you express the problem as 1 + max(left depth, right depth)?
Base case identificationDo you immediately handle None → 0?
DFS vs. BFS fluencyCan you solve it both ways and explain when each is preferred?
Code concisenessDo you write 3 lines or 30?
Verbal reasoningCan you explain why the recursion is correct without tracing every node?

Step 1: Clarifying Questions

1. What is the depth of an empty tree? Zero. No nodes, so depth is 0. This is the base case of your recursion.

2. Is depth counted in nodes or edges? LeetCode counts nodes. A single-node tree has depth 1. Confirm early — some problems use edge-based depth.

3. Can the tree be unbalanced? Yes. Highly skewed trees (effectively linked lists) must work correctly.

4. What’s the maximum number of nodes? 10^4 for LeetCode. Stack depth for recursion is bounded by tree height, which could be up to 10^4 for a skewed tree. Iterative BFS avoids this risk.


Step 2: A First Idea (and Why It’s Already Good)

The recursive solution is already optimal:

def maxDepth(root):
    if root is None:
        return 0
    return 1 + max(maxDepth(root.left), maxDepth(root.right))

This is O(n) time (every node visited once) and O(h) space where h is the tree height (call stack). There’s no simpler formulation. Present it confidently.


Step 3: The Key Insight

The maximum depth of a tree is 1 (for the root) plus the maximum depth of its deeper subtree. This is the recursive definition of depth. The base case is an empty node (None), which has depth 0. Every other node’s depth follows immediately from its children’s depths.

Binary tree [3,9,20,null,null,15,7] with the longest path 3→20→15 highlighted in teal and depth annotations at each level. ---

Step 4: Strategies

Approach A — Recursive DFS (most natural):

  1. Base case: if root is None, return 0.
  2. Recursively compute left depth and right depth.
  3. Return 1 + max(left_depth, right_depth).

Approach B — Iterative BFS (avoids deep call stack):

  1. Use a queue, initialize with the root.
  2. Process level by level, incrementing depth for each level.
  3. Return total depth after all levels are processed.

Python Implementation

Recursive DFS:

from typing import Optional

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if root is None:
            return 0
        return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

Iterative BFS (level-order):

from collections import deque

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if root is None:
            return 0

        depth = 0
        queue = deque([root])

        while queue:
            depth += 1
            for _ in range(len(queue)):
                node = queue.popleft()
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)

        return depth

The BFS version is more code but avoids Python’s recursion limit (~1000 frames by default) on deeply skewed trees.


Time & Space Complexity

ApproachTimeSpace
Recursive DFSO(n)O(h), call stack height
Iterative BFSO(n)O(w), max queue width (widest level)

For a balanced tree, h = O(log n). For a skewed tree, h = O(n). BFS space is O(n/2) in the worst case (a complete binary tree’s last level).


Common Interview Mistakes

  1. Returning depth instead of 1 + depth. Forgetting to count the current node is the most common off-by-one.

  2. Not handling None as the base case. Some candidates check if not root.left and not root.right: return 1, which is correct but harder to reason about than if root is None: return 0.

  3. Confusing depth (nodes) with height (edges). Confirm which definition applies. They differ by 1.

  4. Not mentioning iterative BFS as an alternative. Even if you implement recursion, noting “this can hit Python’s recursion limit on skewed trees, I’d use BFS in production” shows engineering judgment.

  5. Over-explaining the recursion. Strong candidates say one sentence and write three lines of code. Weaker candidates describe every recursive call. Trust the recursion.


What a Strong Candidate Sounds Like

“Maximum depth is 1 plus the greater of the left and right subtree depths. That’s the recursive definition. Base case is an empty node, which has depth 0. The code is three lines. This is O(n) time since we visit every node once, and O(h) space for the call stack where h is the tree height. If we’re worried about a highly skewed tree hitting Python’s recursion limit, I can do this iteratively with BFS — same time complexity, just a queue instead of the call stack.”


Example Interview Dialogue

Interviewer: Why does your recursion work?

Candidate: By induction. For a leaf, both children are None, so we get 1 + max(0, 0) = 1 — correct. For any internal node, the recursion correctly computes the depth of both subtrees first, then adds 1 for the current node. So the result is always the correct depth of the subtree rooted at each node.

Interviewer: What’s the space complexity?

Candidate: O(h) for the call stack, where h is the tree height. For a balanced tree that’s O(log n). For a pathological skewed tree it’s O(n) — essentially a linked list. If that’s a concern I’d use iterative BFS, which uses O(w) queue space where w is the maximum level width.



Practice This in a Mock Interview

Maximum Depth seems too simple to practice. But interviews have a way of making simple problems harder: the interviewer asks you to use BFS instead, or asks for space complexity, or asks why your recursion is correct. The way to answer those fluently is to practice explaining out loud, not just getting the code right.

Start a mock interview for Maximum Depth of Binary Tree on Intervu.


Further reading:

Practice Like It's the Real Interview

Get instant feedback on your approach, communication, and code — powered by AI.

Start a Mock Interview →