Skip to main content
26

Maximum Depth of Binary Tree

Easytreesdfsbfs

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:TreesRead the beginner guide

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.

Understand the problem

  • A leaf is a node with no children: the bottom of a branch.
  • A path from the root down to a leaf goes from the top node, child by child, to a leaf.
  • The depth of that path is how many nodes are on it (counting both the root and the leaf).
  • You want the longest such path. Think of it as "how many floors does this tree have?"

Example 1

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

    3
   / \
  9  20
    /  \
   15   7

The path 3 → 20 → 15 (or 3 → 20 → 7) has 3 nodes. The path 3 → 9 has only 2.

Example 2

text
Input:  root = [1, null, 2]
Output: 2

1 has only a right child 2: the path 1 → 2 has 2 nodes.

Example 3

text
Input:  root = []
Output: 0

An empty tree has no nodes, so its depth is 0.

How trees are written in the tests: level by level, top to bottom, left to right, with null for a missing child. [] is an empty tree.

Constraints

  • 0 <= number of nodes <= 10^4

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    The depth of a tree is 1 (for the root) plus the depth of its deeper subtree, and an empty tree has depth 0.

    Thinking recursively

    As with most tree problems, ask: "if I already knew the answer for both subtrees, how would I get the answer for this node?"

    • The left subtree has depth L, the right subtree has depth R.
    • The longest path from this node goes through this node (1) and continues down the deeper side.
    • So the answer is 1 + max(L, R).

    Base case: an empty tree has depth 0.

    Step by step

    text
        3
       / \
      9  20
        /  \
       15   7

    The recursion goes all the way down first, then the answers come back up:

    NodeLeft depthRight depthDepth = 1 + max
    90 (null)0 (null)1
    15001
    7001
    201 (15)1 (7)2
    31 (9)2 (20)3

    Answer: 3.

    Another way: count the levels (BFS)

    You can also go level by level with a queue (this is BFS, breadth-first search), and count how many levels there are:

    1. Put the root in a queue.
    2. While the queue isn't empty: the nodes in it right now are one level. Count one more level, remove exactly that many nodes, and add their children to the queue.
    3. The number of levels is the depth.

    The Python reference solution uses this approach, so you can see both. BFS also avoids very deep recursion on a lopsided tree.

    The code

    The reference solution is below, with comments on every important line (recursion in JavaScript/TypeScript, BFS in Python).

    How fast is it?

    • Time: O(n). Every node is visited once.
    • Memory: O(h) for the recursion, where h is the height. O(w) for BFS, where w is the number of nodes on the widest level.

    Common mistakes

    • Counting edges instead of nodes. This problem counts nodes: a single node has depth 1, not 0.
    • Returning 1 for an empty tree. No nodes means depth 0.
    • Using min instead of max. That's a different problem ("minimum depth"), with its own trap: a node with only one child isn't a leaf.

    Going deeper

    The BFS "process one level at a time" pattern, where you read the queue's size before each level, is the core of Binary Tree Level Order Traversal. Recursion that returns a number computed from both children is the core of Binary Tree Maximum Path Sum.

    Reference solution

    js
    /**
     * @param {TreeNode | null} root
     * @return {number}
     */
    export default function maxDepth(root) {
      // Base case: an empty tree has no nodes, so depth 0.
      if (!root) return 0
      // This node (1) plus the deeper of its two subtrees.
      return 1 + Math.max(maxDepth(root.left), maxDepth(root.right))
    }
    ts
    export default function maxDepth(root: TreeNode | null): number {
      // Base case: an empty tree has no nodes, so depth 0.
      if (!root) return 0
      // This node (1) plus the deeper of its two subtrees.
      return 1 + Math.max(maxDepth(root.left), maxDepth(root.right))
    }
    python
    from collections import deque
    
    
    def max_depth(root: TreeNode | None) -> int:
        # BFS: count the levels of the tree, one level at a time.
        if root is None:
            return 0
        depth = 0
        queue = deque([root])  # a queue: add at the back, take from the front
        while queue:
            depth += 1  # everything in the queue right now is one level
            # Take exactly this level's nodes, and queue up their children (the next level).
            for _ in range(len(queue)):
                node = queue.popleft()
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
        return depth