Maximum Depth of Binary Tree (LeetCode 104): Solution and Explanation

Easy
Tree
Depth First Search
Breadth First Search
Binary Tree

Given the root of a binary tree, return its maximum depth, which is the number of nodes on the longest path from the root down to any leaf. An empty tree has depth 0.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

You could try to track depth explicitly: walk every root-to-leaf path, count its nodes, and keep the largest count. That works, but it is more bookkeeping than the problem needs. Trees are recursive structures, and a lot of tree problems collapse once you ask what a node needs from its children to answer the question for itself.

Here the answer is clean. The deepest path that starts at a node goes through the node itself and then continues down whichever child subtree is deeper. So the depth of a tree is one (for the root) plus the larger of the depths of its left and right subtrees. The base case is the empty tree, which has depth 0. That definition is the whole algorithm, and it translates line for line into code.

This is a post-order depth-first search: each call waits for both children to report their depths before computing its own. Every node is visited exactly once, so the work is linear. The only cost beyond that is the call stack, which grows as deep as the tree itself. For a balanced tree that is about log n frames; for a tree that is a straight chain it is n frames, which in Python can approach the default recursion limit on very deep inputs.

The same pattern, where each node combines answers returned by its children, solves many related problems with only small changes. Balanced Binary Tree compares the two child heights, Diameter of Binary Tree adds them, and Maximum Path Sum adds the best child gains. Getting comfortable with this three-line recursion pays off across the whole tree category.

Approach: Recursive depth-first search

  1. If root is None, return 0, since an empty subtree contributes no depth.
  2. Recursively compute the depth of root.left.
  3. Recursively compute the depth of root.right.
  4. Return 1 + max(left depth, right depth), counting the current node on top of the deeper subtree.

Step-by-step example

root = [3, 9, 20, null, null, 15, 7]
  1. The tree has 3 at the root, 9 as its left child (a leaf), and 20 as its right child with children 15 and 7.
  2. maxDepth(9): both children are None and return 0, so it returns 1 + max(0, 0) = 1.
  3. maxDepth(15) and maxDepth(7) are leaves and each return 1.
  4. maxDepth(20) returns 1 + max(1, 1) = 2.
  5. maxDepth(3) returns 1 + max(1, 2) = 3, which is the answer.

Code: Python, Java, C++

1class Solution:
2    def maxDepth(self, root: Optional[TreeNode]) -> int:
3        if not root:
4            return 0
5        return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

Time and space complexity

Time

O(n)

Each of the n nodes is visited exactly once, and each visit does constant work besides its two recursive calls.

Space

O(h)

The recursion stack holds one frame per level of the current path, where h is the tree height. That is O(log n) for a balanced tree and O(n) for a completely skewed one.

Other approaches

Breadth-first level count (time O(n), space O(w))

Use a queue to process the tree level by level and count how many levels you process. It avoids recursion entirely, which helps on very deep trees, but the queue can hold an entire level, up to about n/2 nodes.

Iterative DFS with an explicit stack (time O(n), space O(h))

Push (node, depth) pairs onto a stack and track the largest depth popped. It mirrors the recursive version without risking a recursion limit error.

Common mistakes

  • Returning 1 for an empty tree. A None root has depth 0, and returning 1 would make every leaf report depth 2.
  • Counting edges instead of nodes. This problem measures depth in nodes, so a single-node tree has depth 1, not 0.
  • Using min by mistake, or confusing this with Minimum Depth. Minimum depth must ignore missing children, so the logic is not symmetric.
  • Relying on recursion for a degenerate tree with tens of thousands of nodes in Python, where the default recursion limit is about 1,000. The iterative versions avoid that.

Frequently asked questions

What is the time complexity of finding the maximum depth of a binary tree?

O(n), because every node must be visited once to be sure no deeper path exists. The space is O(h) for the recursion stack, where h is the height.

DFS or BFS for maximum depth?

Both are O(n) time. Recursive DFS is shorter and uses O(h) space, while BFS counts levels with a queue and uses space proportional to the widest level.

Is depth counted in nodes or edges?

In this problem it is counted in nodes along the longest root-to-leaf path. Some textbooks define height in edges, which gives a value one smaller.

Can this be done without recursion?

Yes. A level-order traversal with a queue, or a DFS with an explicit stack of (node, depth) pairs, gives the same answer iteratively.