Maximum Depth of Binary Tree
easyNeetCode 150treesrecursionbfs
Problem
Given the root of a binary tree, return its maximum depth, defined as the number of nodes along the longest path from the root down to a leaf.
Examples
Input: [3, 9, 20, null, null, 15, 7]
Output: 3
The deepest path passes through three nodes.
Input: empty tree
Output: 0
No nodes means depth zero.
Constraints
- • 0 <= number of nodes <= 10^4
- • -100 <= node value <= 100
Hints(tap to reveal)
- 1. Depth is one plus the deeper subtree.
- 2. Base case is a null node with depth zero.
Optimal approach(spoiler)
- Return zero for a null node.
- Recurse to find the depth of the left and right subtrees.
- Return one plus the larger of the two.
- A breadth-first level count is an iterative alternative.
- O(n) time, O(h) space.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor