Skip to the solution
EasyDSA13 min read

How do you find the maximum depth of a binary tree?

89 views

The problem

Question presented to candidate: "Given the root of a binary tree, write a Python function that returns its maximum depth: the number of nodes on the longest path from the root down to a leaf. Start with whatever is simplest, then tell me what happens if the tree is a very long chain."

What a strong answer should cover:

  • The recurrence depth(None) = 0, depth(node) = 1 + max(depth(left), depth(right)), and that it is a postorder traversal.
  • O(n) time because every node is visited once; O(h) space for the call stack, which is O(n) for a chain.
  • An iterative alternative: BFS counting levels with collections.deque, or a stack of (node, depth) tuples.
  • Clarifying nodes versus edges and the empty-tree answer; awareness of the minimum-depth trap with one-child nodes.
  • Python specifics: the default recursion limit of 1000 means a 1000-deep chain raises RecursionError; use deque.popleft() not list.pop(0); tuple unpacking node, d = stack.pop() keeps the stack version short.

Clarifying questions expected:

  • "Is depth counted in nodes or edges, and what should an empty tree return?"
  • "Could the tree be very deep, like a linked list?"

Code / implementation expected: Yes โ€” a recursive Python function, ideally followed by an iterative BFS or stack version.

  • trees
  • recursion

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonRecursive maximum depth (and the minimum-depth trap) on five trees
PythonIterative BFS and DFS: depth plus peak queue and stack sizes

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 37 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

How do you solve the Two Sum problem efficiently?

Continue