PPractick

DSA interview question

Maximum Depth of a Binary Tree

Medium · Data structures · Topics: tree, dfs, recursion

The problem

A UI framework lays out nested components as a tree, and deeply nested layouts render slowly. The profiler reports the maximum depth: the number of nodes on the longest path from the root down to a leaf. The recursive answer is one line. An empty tree has depth 0, and otherwise the depth is 1 plus the deeper of the two subtrees. A BFS that counts levels gives the same number without recursion.

Example: [3, 9, 20, null, null, 15, 7] → 3.

Function signature

int maxDepth(TreeNode* root);

Test cases

Input (level order)OutputExplanation
[3, 9, 20, null, null, 15, 7]33 → 20 → 15
[1, null, 2]2
[1, 2, null, 3, null, 4]4A left chain
[1]1
[]0

(Confirm: depth counts nodes, not edges; an empty tree has depth 0.)

How interviewers phrase it

Clarifying questions to ask

  1. Nodes or edges? (Nodes.)
  2. Can the tree be empty? (Yes, so return 0.)
  3. Could it be very deep? (Then prefer BFS or an explicit stack.)

Follow-ups to expect

  1. "Recursive formula?"
  2. "Iterative?"
  3. "Minimum depth?"
  4. "How does this relate to 'balanced tree' and 'diameter'?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in