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.
โข 0 โค number of nodes โค 10โดโข -100 โค Node.val โค 100
02
Section Two ยท Approach 1
BFS Level Count โ O(n)
Use a queue for level-order traversal. Count the number of levels โ that's the depth. Process all nodes at each level before moving to the next.
03
Section Three ยท Approach 2
Recursive DFS โ O(n)
The depth of a tree = 1 + max(depth of left subtree, depth of right subtree). Base case: null node has depth 0. This is the canonical bottom-up tree recursion.
๐ก Mental model: Ask each child "how deep are you?" Take the bigger answer, add 1 (for yourself). Leaves answer 1 (they have no children, so max(0,0)+1). The root's answer is the tree's depth.
๐ฏ Foundation pattern:
This "ask children, combine answers" pattern is the basis of most tree problems: max depth, min depth, diameter, balanced check, path sum.
classSolution:
defmaxDepth(self, root) -> int:
if not root: return0return1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
06
Section Six ยท Analysis
Complexity Analysis
Approach
Time
Space
Recursive DFS
O(n)
O(h) โ call stack
Iterative BFS
O(n)
O(n) โ queue
07
Section Seven ยท Edge Cases
Edge Cases & Pitfalls
Case
Input
Why It Matters
Empty
null
Depth = 0.
Single node
[1]
Depth = 1.
Skewed
1โ2โ3โ4
Depth = n. Stack depth = n (worst case).
โ Common Mistake: Returning 1 for null nodes instead of 0. Null means "no node here" โ depth 0. A leaf is depth 1 because it exists. Off-by-one errors cascade through the entire tree.