Maximum Depth of Binary Tree
Maximum Depth of Binary Tree is a easy trees & bst problem solved with the recursion pattern.
The best approach, recursive dfs, runs in O(n) time and O(h) space.
Below are 2 approaches in Java, from level order (bfs) up.
Problem
Return the maximum depth of a binary tree: the number of nodes on the longest path from the root down to a leaf.
Examples
Example 1
- Input
root = [3, 9, 20, null, null, 15, 7]- Output
3
Example 2
- Input
root = [1, null, 2]- Output
2
Constraints
- The tree has
0to10^4nodes.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.
| Approach | Time | Space |
|---|---|---|
| Level order (BFS) | O(n) | O(w) |
| Recursive DFS | O(n) | O(h) |
1Level order (BFS)
O(n)O(w)w = maximum width of the tree.Count the number of levels with a queue.
- Process the queue level by level; depth++ per level.
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
Queue<TreeNode> q = new ArrayDeque<>();
q.add(root);
int depth = 0;
while (!q.isEmpty()) {
depth++;
for (int i = q.size(); i > 0; i--) {
TreeNode n = q.poll();
if (n.left != null) q.add(n.left);
if (n.right != null) q.add(n.right);
}
}
return depth;
}
}2Recursive DFS
O(n)O(h)An empty tree has depth 0. Any other node is one deeper than the deeper of its two subtrees.
- if root == null return 0.
- return 1 + max(maxDepth(left), maxDepth(right)).
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}Edge cases to test
- Empty tree (0)
- Skewed tree (depth n)
Hints
Hint 1
depth(node) = 1 + max(depth(left), depth(right)).
FAQ
What is the best time complexity for Maximum Depth of Binary Tree?
Recursive DFS runs in O(n) time and O(h) extra space.
Which pattern does Maximum Depth of Binary Tree use?
It is a trees & bst problem that uses the recursion pattern. Other problems with the same pattern: Binary Tree Inorder Traversal (Recursive), Binary Tree Preorder Traversal (Recursive), Binary Tree Postorder Traversal (Recursive).
Is there a brute force solution for Maximum Depth of Binary Tree?
Yes. Level order (BFS) takes O(n) time and O(w) space. Count the number of levels with a queue.
Which edge cases should I test for Maximum Depth of Binary Tree?
Empty tree (0); Skewed tree (depth n).