Maximum Depth of Binary Tree
Count the nodes on the longest root-to-leaf path by asking each subtree for its own depth.
The problem
You get the root of a binary tree. Return its maximum depth: the number of nodes on the longest path from the root down to a leaf. An empty tree has depth 0.
Input root = [5, 8, 2, null, 4, 9, null, 7]
Output 4
The longest path is 5, 8, 4, 7, which has 4 nodes.
Input root = [1, 2, null, 3, null, 4]
Output 4
Each node has only a left child, so the tree is a chain of 4 levels.
How to spot the pattern
- The answer for a tree can be built from the same answer for its two subtrees.
- You need a property of the whole tree (its height), so every node has to be looked at once.
The idea
The depth of a tree is one level for the root plus the depth of its deeper subtree. That is the same question asked on a smaller tree, so a recursive function answers it directly. The recursion stops at an empty subtree, whose depth is 0.
Brute force: Copy out every root-to-leaf path and measure each one, which costs O(n * h) time because the top of the tree is copied again for every leaf.
Step by step
- 1If the node is null, return 0.
- 2Find the depth of the left subtree and of the right subtree with the same function.
- 3Return 1 plus the larger of the two depths.
See the pattern move
The tree dfs and bst pattern on a small example. Step through it, or press play.
Code
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))Complexity
Time
O(n)
Space
O(h)
Every node is visited once; the recursion stack holds one call per level of the current path, up to the height h (n for a chain, about log n for a balanced tree).
Watch out for
- Counting edges instead of nodes: a single node has depth 1 here, not 0.
- Returning 1 for a null child, which adds a level that does not exist under every leaf.
Follow-up questions
Can you do it without recursion?
Run BFS level by level and count the levels, or keep a stack of (node, depth) pairs. Both are O(n) time, and BFS never needs a deep call stack.
How would you find the minimum depth instead?
A node with one child is not a leaf, so you can't just take the smaller side: a missing child has to be ignored. BFS that stops at the first leaf it meets is the cleanest way.
In Hinglish
Har node apne dono bachchon se poochta hai ki tumhari depth kitni hai, badi wali mein 1 jodo aur upar bhej do. Null node ki depth 0 hai.