Maximum Depth of Binary Tree
Problem
Given the
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.
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.
Examples
Example 1
Input: root = [3,9,20,null,null,15,7]
Output: 3
Example 2
Input: root = [1,null,2]
Output: 2
Key Insight
Depth of a node = 1 + max(depth of left subtree, depth of right subtree)
Depth = 1 + max(left depth, right depth). Null has depth 0.
How to Approach This Problem
Pattern Recognition: When you see keywords like
maximum depth of binary tree trees,
think Tree Traversal.
Step-by-Step Reasoning
1
The depth of an empty tree (null) is:
Answer: 0
No nodes means depth is 0. This is the foundation for counting.
2
A tree with just a root (no children) has depth:
Answer: 1
One node = depth 1. Base case 0 + 1 = 1.
3
depth(node) = ?
Answer: 1 + max(depth(left), depth(right))
Take the deeper subtree, add 1 for current node.
4
We use max because:
Answer: We want the longest path
We're finding maximum depth. The longest path determines it.
5
This is an example of:
Answer: Post-order traversal
We process children first, then combine results at parent. That's post-order.
6
For iterative solution, we can use:
Answer: BFS and count levels
Each level of BFS = one depth. Count total levels.
Solution
def maxDepth(root: TreeNode) -> int:
if not root:
return 0
left_depth = maxDepth(root.left)
right_depth = maxDepth(root.right)
return 1 + max(left_depth, right_depth)
Complexity Analysis
| Time | O(n) |
|---|---|
| Space | O(h) |
Master This Pattern
Build intuition with interactive MCQs. Practice Tree Traversal problems in the LeetEye app.
Download LeetEye Free