Maximum Depth of Binary Tree

Free with account Updated Nov 19, 2026 · 5 min read
On this page

    Problem statement

    Given the root of a binary tree, return its maximum depth: the number of nodes on the longest path from the root down to a leaf. An empty tree has depth 0, and a tree with just a root has depth 1.

    The simplest tree-recursion question, and a common opener: the interviewer wants a correct base case, a clear recurrence, and an answer to "what if the tree is very deep?". Original problem: LeetCode 104.

    Example

    The longest root-to-leaf path is 5 → 8 → 9 → 7, four nodes, so the depth is 4.
    The longest root-to-leaf path is 5 → 8 → 9 → 7, four nodes, so the depth is 4.
    Input:  root = [5, 3, 8, null, 4, null, 9, 7]     # level order, null = missing child
    Output: 4                                          # 5 -> 8 -> 9 -> 7
    Input:  root = []      ->  0
    Input:  root = [1]     ->  1

    Constraints (assumed)

    • 0 ≤ number of nodes ≤ 10⁵ (the tree may be very unbalanced).

    What this question tests

    • Writing a recursive function with the right base case.
    • Knowing the iterative alternatives (BFS by levels, DFS with a stack).
    • Thinking about recursion depth on skewed trees.

    Questions to ask first

    1. Depth in nodes or in edges? (Here: nodes, so a single root is 1.)
    2. What should an empty tree return? (Here: 0.)
    3. How deep can the tree be? A 10⁵-node chain affects the choice between recursion and iteration.
    4. Is it a binary tree, or can nodes have many children? (Here: binary.)