Maximum Depth of Binary Tree - 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. Think of it as measuring how "tall" your tree is - counting every level from top to bottom.
Example: If you have a tree that goes Root โ Child โ Grandchild, that's a depth of 3 nodes.
Note: An empty tree has a depth of 0, and a single node has a depth of 1.
Input & Output
example_1.py โ Standard Binary Tree
$
Input:
root = [3,9,20,null,null,15,7]
โบ
Output:
3
๐ก Note:
The tree has 3 levels: root(3) โ level 2(9,20) โ level 3(15,7). The maximum depth is 3.
example_2.py โ Single Path Tree
$
Input:
root = [1,null,2]
โบ
Output:
2
๐ก Note:
The tree has only a right path: 1 โ 2. The maximum depth is 2 nodes along this path.
example_3.py โ Single Node
$
Input:
root = [5]
โบ
Output:
1
๐ก Note:
A tree with just one node (the root) has a depth of 1.
Visualization
Tap to expand
Understanding the Visualization
1
Start at leaf level
Childless nodes (leaves) represent generation 1 - they have depth 1
2
Build upward
Each parent's generation depth = 1 + max(children's depths)
3
Propagate to root
This calculation bubbles up to the root, giving total tree depth
4
Handle edge cases
Empty tree has depth 0, single node has depth 1
Key Takeaway
๐ฏ Key Insight: Each node only needs to know its children's maximum depth and add 1 - the recursive structure naturally solves the problem!
Time & Space Complexity
Time Complexity
O(n)
We visit each node exactly once in the tree
โ Linear Growth
Space Complexity
O(h)
Recursion stack depth equals tree height h. O(log n) for balanced tree, O(n) for skewed tree
โ Linear Space
Constraints
- The number of nodes in the tree is in the range [0, 104]
- -100 โค Node.val โค 100
- Tree depth will not exceed typical recursion stack limits
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code