← Back to Algorithms, page 3

algorithms-0052 · Easy fresher

Maximum depth of a binary tree: return the number of nodes on the longest root-to-leaf path, with a recursive and a breadth-first solution.

The depth of a tree is 1 plus the larger depth of its two subtrees, and an empty tree has depth 0. That recursion is O(n) time and O(h) stack. A BFS that counts levels gives the same answer without recursion, using O(width) queue space. Minimum depth is a related trap: a node with one child is not a leaf.

Full answer

Problem

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

Example: the tree 3 -> 9, (20 -> 15, 7) has depth 3.

Constraints: 0 to 10^4 nodes. The tree is not guaranteed to be balanced.

Brute force

Enumerate every root-to-leaf path, measure each one, and take the longest. Collecting paths explicitly costs O(n * h) time and memory because each path is copied.

Optimal approach

Recursive: depth(None) = 0, depth(node) = 1 + max(depth(left), depth(right)).

Iterative: BFS with a queue. Process the queue one level at a time (loop len(q) times), and increase a counter after each level. The counter at the end is the depth.

Why it works

The longest path from a node goes down into whichever subtree is deeper, so the depth of the node is one more than the deeper child. The base case of 0 for an empty subtree makes leaves come out as 1. In BFS every level is fully processed before the next begins, so the number of levels processed equals the depth.

Complexity

Both versions visit each node once: O(n) time. Recursion uses O(h) stack space; BFS uses O(w) where w is the widest level (up to about n/2 in a complete tree).

Code

python
from collections import deque


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


def max_depth(root):
    """Recursive: depth = 1 + max(child depths). O(n) time, O(h) stack."""
    if root is None:
        return 0
    return 1 + max(max_depth(root.left), max_depth(root.right))


def max_depth_bfs(root):
    """Level by level with a queue; no recursion. O(n) time, O(width) space."""
    if root is None:
        return 0
    depth, q = 0, deque([root])
    while q:
        depth += 1
        for _ in range(len(q)):
            node = q.popleft()
            if node.left:
                q.append(node.left)
            if node.right:
                q.append(node.right)
    return depth


def min_depth(root):
    """Shortest root-to-leaf path: a node with one child is not a leaf."""
    if root is None:
        return 0
    if not root.left or not root.right:
        return 1 + min_depth(root.left or root.right)
    return 1 + min(min_depth(root.left), min_depth(root.right))


if __name__ == "__main__":
    t = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
    for f in (max_depth, max_depth_bfs):
        assert f(t) == 3
        assert f(None) == 0
        assert f(TreeNode(1)) == 1
        assert f(TreeNode(1, None, TreeNode(2, None, TreeNode(3)))) == 3
    assert min_depth(t) == 2
    assert min_depth(TreeNode(1, TreeNode(2))) == 2      # not 1: the root is not a leaf
    chain = None
    for v in range(3000):
        chain = TreeNode(v, chain)
    assert max_depth_bfs(chain) == 3000
    print("all tests passed")

Save as b52_max_depth.py and run python3 b52_max_depth.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty tree (0). Single node (1). A right-only chain (depth equals n; the BFS version avoids deep recursion). For minimum depth, a node with only one child must recurse into that child; taking min with the empty side would wrongly return 1.

Pattern

Post-order "combine children" recursion: compute a value for each subtree and merge at the parent. The same template gives subtree size, balanced-tree checks, diameter and maximum path sum.

python
from collections import deque


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


def max_depth(root):
    """Recursive: depth = 1 + max(child depths). O(n) time, O(h) stack."""
    if root is None:
        return 0
    return 1 + max(max_depth(root.left), max_depth(root.right))


def max_depth_bfs(root):
    """Level by level with a queue; no recursion. O(n) time, O(width) space."""
    if root is None:
        return 0
    depth, q = 0, deque([root])
    while q:
        depth += 1
        for _ in range(len(q)):
            node = q.popleft()
            if node.left:
                q.append(node.left)
            if node.right:
                q.append(node.right)
    return depth


def min_depth(root):
    """Shortest root-to-leaf path: a node with one child is not a leaf."""
    if root is None:
        return 0
    if not root.left or not root.right:
        return 1 + min_depth(root.left or root.right)
    return 1 + min(min_depth(root.left), min_depth(root.right))


if __name__ == "__main__":
    t = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))
    for f in (max_depth, max_depth_bfs):
        assert f(t) == 3
        assert f(None) == 0
        assert f(TreeNode(1)) == 1
        assert f(TreeNode(1, None, TreeNode(2, None, TreeNode(3)))) == 3
    assert min_depth(t) == 2
    assert min_depth(TreeNode(1, TreeNode(2))) == 2      # not 1: the root is not a leaf
    chain = None
    for v in range(3000):
        chain = TreeNode(v, chain)
    assert max_depth_bfs(chain) == 3000
    print("all tests passed")

Recursive and level-by-level versions; min_depth is included to show the one-child trap.

Complexity

Time: O(n). Space: O(h) recursive, O(w) BFS. h is the height and w the maximum width; for a balanced tree h is O(log n) but w is O(n).

By level

Fresher: Writes the three-line recursion with the correct base case and walks through a small example. Can also count levels with a queue.

Mid: Compares DFS and BFS space in terms of height and width and picks one for a given tree shape. Handles minimum depth correctly and extends the idea to a balanced-tree check.

Senior: Explains when BFS finds minimum depth faster because it can stop at the first leaf, which matters for wide but shallow trees. Discusses iterative DFS with an explicit (node, depth) stack and the memory profile of each choice on large trees.

Key points

  • depth = 1 + max(left, right), empty tree = 0
  • BFS counts levels by processing len(q) nodes per round
  • Both are O(n) time
  • Space depends on height (DFS) or width (BFS)
  • Minimum depth needs the one-child rule

Common mistakes

  • Returning 1 for an empty tree
  • Counting edges instead of nodes without saying so
  • Using min with an empty child for minimum depth
  • Forgetting the recursion limit for chain-shaped trees

Follow-ups

  • How do you check whether a tree is height-balanced in one pass?
  • How would you compute the minimum depth efficiently on a very wide tree?
  • What changes for an n-ary tree?

Tips

  • Say whether depth counts nodes or edges
  • Mention the BFS version as the answer to deep trees
  • Give the space bound in terms of h and w

Evaluation rubric

  • Correct recursion and base case
  • Working BFS level count
  • Correct space analysis
  • Handles the minimum-depth variant