104. Maximum Depth of Binary Tree
easyCompute the maximum depth (root-to-leaf height) of a binary tree. The canonical recursion warm-up — every tree problem builds on this pattern.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Constraints
The number of nodes in the tree is in the range [0, 10^4].-100 <= Node.val <= 100
Examples
Example 1
root = [3,9,20,null,null,15,7]3Example 2
root = [1,null,2]2Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
Recursion: depth(node) = 1 + max(depth(node.left), depth(node.right)).
Hint 2
Base case: depth(null) = 0.
Hint 3
Iterative BFS works too — count levels until the queue is empty.
Solution approach
Reveal approach
Recursive DFS. If the node is null, return 0. Otherwise return 1 + max(depth(node.left), depth(node.right)). Each node contributes 1 to its own depth and lifts the maximum of its subtrees' depths. O(n) time visiting each node once; O(h) space for the recursion stack (h = tree height, up to n in the worst case of a skewed tree). Iterative alternative: BFS with a queue, incrementing a level counter per processed level — also O(n) time with O(width) space.
Complexity
- Time
- O(n)
- Space
- O(h)
Related patterns
- dfs
- bfs
- recursion
Related problems
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
- Microsoft
Practice these live with InterviewChamp.AI
Drill Maximum Depth of Binary Tree and Trees problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →