Skip to content
Problem 104 · LeetCode 104(opens in a new tab)

Maximum Depth of Binary Tree

EasyBreadth-first search

You get root, the top node of a binary tree. The depth of the tree is how many nodes sit on the longest path that starts at the root and goes down to a leaf (a node with no children).

Return that depth. An empty tree has depth 0, and a tree with only a root has depth 1.

Example 1

Input:  root = [6, 2, 9, null, null, 4, 11]
Output: 3
Why:    6 → 9 → 4 has three nodes; 6 → 2 has two
2 more examples and the constraints

Example 2

Input:  root = [4, 1, null, 3]
Output: 3
Why:    a chain down the left side: 4 → 1 → 3

Example 3

Input:  root = []
Output: 0
Why:    no nodes, so no path at all

Constraints

  • 0 ≤ number of nodes ≤ 10,000
  • −100 ≤ each node value ≤ 100

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Recursive DFSO(n)
  2. Level by level (BFS)O(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 nodesVerdict
Recursive DFSO(n)
Shortest code; deep chains strain the stack
Level by level (BFS)O(n)
Best; same speed, no recursion

n = number of nodes, h = height of the tree, w = widest level.

Edge cases to test

  • Empty tree. [] must give 0. Check for a missing root before touching its children.
  • Only a root. [42] gives 1: the root is a path of one node.
  • A long chain. Every node has one child, so the depth equals the node count. Recursion goes that many calls deep.
  • Lopsided tree. The deepest leaf can be on either side; always compare both subtrees.

Common mistakes

  • Counting edges instead of nodes, so a one-node tree returns 0.
  • Returning 1 for an empty tree because the null check comes after the + 1.
  • In BFS, reading the queue's size inside the inner loop while it grows, so two levels get counted as one.

How to talk through it

  1. 1Clarify. Is depth counted in nodes or edges? What should an empty tree return? How deep can the tree get?
  2. 2State the recursion. Depth is 0 for an empty tree, otherwise 1 + the larger depth of the two subtrees.
  3. 3Code it, then name the risk. Two lines. The call stack is as deep as the tree, which can be 10,000 for a chain.
  4. 4Offer the loop. BFS with a queue: each round is one level, and the number of rounds is the depth.
  5. 5Test out loud. Run an empty tree, a single node and a one-sided chain before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?