Maximum Depth of Binary Tree solution explained
The maximum depth of a binary tree is 0 for an empty tree and otherwise 1 plus the larger of the depths of the left and right subtrees, which a short recursive function computes in O(n) time. To avoid deep recursion on a lopsided tree, walk the tree level by level with a queue and count the levels instead; that is also O(n) time.
By Evin JohnPublished 6 min read
The question in plain words
Given the root of a binary tree, report how many nodes lie on the longest path that starts at the root and ends at a leaf. A leaf is a node with no children. An empty tree has depth 0 and a single node has depth 1. Some textbooks count edges instead of nodes, which gives one less, so confirm which one the interviewer means.
| Tree | Depth | Longest path |
|---|---|---|
| 10 / 4, 17 / -, -, 12, 25 / -, -, -, 30 | 4 | 10 → 17 → 25 → 30 |
| 8 | 1 | Just the root |
| empty | 0 | No nodes |
| 1 / 2, - / 3, - / 4, - | 4 | A chain leaning left |
Why it opens so many tree rounds
It is the smallest problem that tests whether you can think recursively about trees: trust the answer for each subtree and combine the two. Many harder questions are this same shape with a different combine step, such as checking balance, finding the diameter or summing paths. Interviewers often ask it first, then ask for the iterative version to see whether you know breadth-first search as well.
Follow-ups
- Minimum depth. The nearest leaf. With BFS, return as soon as you meet a leaf. In recursion, be careful: a node with one child is not a leaf.
- Is the tree height-balanced? Compute depths bottom-up and fail fast when two siblings differ by more than one.
- Diameter. The longest path between any two nodes; at each node, left depth plus right depth is a candidate.
- Depth of an n-ary tree. Take the maximum over all children instead of two.
A brute-force view
List every root-to-leaf path and take the longest. That is easy to describe, and with depth-first search it is already O(n) in time if you only track path lengths instead of copying paths. Copying every path, though, can cost O(n log n) for balanced trees and O(n²) for long chains with side leaves. The recursive formula below is the same search without storing paths.
The recursive answer
An empty tree has depth 0. Any other tree has depth one more than its deeper subtree. That is the whole function. Each node is visited once, so time is O(n). The call stack grows to the height of the tree: about log n for a balanced tree and n for a chain.
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def max_depth(root):
if root is None:
return 0
return 1 + max(max_depth(root.left), max_depth(root.right))Python's default recursion limit is around a thousand frames, so a chain of a few thousand nodes raises an error. Raising the limit is a patch; the level walk below avoids the problem entirely, which is worth saying when the interviewer asks about very deep trees.
Counting levels with a queue
Process the tree one level at a time. Start with a list holding only the root. While the list is not empty, add one to the depth and replace the list with all the children of its nodes. When there are no more children, the count is the depth. Memory is the size of the widest level, which can be about n / 2 in a full tree but stays small for a chain.
def max_depth_by_levels(root):
depth = 0
level = [root] if root else []
while level:
depth += 1
level = [child for node in level for child in (node.left, node.right) if child]
return depthclass TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function maxDepth(root) {
if (root === null) return 0;
let depth = 0;
let level = [root];
while (level.length > 0) {
depth++;
const next = [];
for (const node of level) {
if (node.left !== null) next.push(node.left);
if (node.right !== null) next.push(node.right);
}
level = next;
}
return depth;
}A third option is depth-first search with an explicit stack of (node, depth) pairs, keeping the largest depth seen. It has the same O(n) time and O(h) memory as recursion, without the language's call-stack limit.
Complexity
| Approach | Time | Extra memory | Watch out for |
|---|---|---|---|
| Recursion | O(n) | O(h) call stack | Stack limits on very deep trees |
| Level-by-level BFS | O(n) | O(w) | Wide trees hold many nodes at once |
| DFS with an explicit stack | O(n) | O(h) | Slightly more code |
Trees to test
- An empty tree, which must return 0.
- A single node.
- A tree where the deepest leaf is on the right side only.
- A long chain, to check stack behavior and that one-child nodes are handled.
- A perfect tree, where every level is full.
Slips to avoid
- Returning 1 for an empty tree, or mixing node counts and edge counts.
- Counting nodes instead of levels in the BFS version by adding one per node popped.
- Using the minimum-depth logic by mistake, or treating a one-child node as a leaf.
- Calling the function twice per child in a misplaced comparison, which turns linear work into exponential.
How to explain it out loud
Fictional example
- Candidate
- An empty tree has depth zero; otherwise it is one plus the deeper of the two subtrees. Each node is visited once, so it is linear time.
- Candidate
- Memory is the recursion depth, which is the tree's height. For a long chain that can overflow the stack, so I can also count levels with a queue.
- Candidate
- In that version I replace the current level with all its children and add one each time, until no children are left.
Where to go next
Invert Binary Tree uses the same recursive shape with a different action at each node. Binary Tree Level Order Traversal returns the levels themselves instead of counting them. For a change of pace back to arrays and pointer-chasing, try Find the Duplicate Number.
How Natively fits your practice
Interviewers often sketch a tree rather than type it out. When you practice on Mac or Windows, Natively can take a screenshot of that sketch and the question, then suggest the recursive formula and the level walk with their costs, so you can compare them with your own plan. If you rehearse out loud, the transcript tells you whether you mentioned stack depth before being asked. Here is the AI interview assistant.
Questions people ask
How do you find the maximum depth of a binary tree?
An empty tree has depth 0; otherwise the depth is 1 plus the larger depth of the two subtrees. A recursive function computes it in O(n) time.
How do you find the depth without recursion?
Walk the tree level by level: start with the root, replace the current level with all its children, and add one for each level until none remain.
What is the space complexity of maximum depth?
O(h) for recursion, where h is the height, which is n for a chain. The level-by-level version uses memory equal to the widest level.
Is depth counted in nodes or edges?
Usually in nodes, so a single node has depth 1. Some sources count edges, which gives one less; ask which one the interviewer means.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
