LeetCode ยท #104

Maximum Depth of Binary Tree Solution

Given the root of a binary tree, return its maximum depth โ€” the number of nodes along the longest path from root to the farthest leaf.

01
Section One ยท Problem

Problem Statement

๐Ÿท๏ธ

Difficulty

Easy

๐Ÿ”—

LeetCode

Problem #104

๐Ÿ—๏ธ

Pattern

Recursion โ€” bottom-up depth

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.

Example
Input: [3, 9, 20, null, null, 15, 7] Output: 3 // 3 depth 1 // / \ // 9 20 depth 2 // / \ // 15 7 depth 3
Constraints
โ€ข 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.
  • Master this recurrence first.
04
Section Four ยท Trace

Visual Walkthrough

Bottom-up depth calculation
3 depth = 3 9 depth = 1 20 depth = 2 15 depth=1 7 depth=1 BOTTOM-UP COMPUTATION Node 9: 1 + max(0, 0) = 1 Node 15: 1 + max(0, 0) = 1 Node 7: 1 + max(0, 0) = 1 Node 20: 1 + max(1, 1) = 2 Node 3: 1 + max(1, 2) = 3 โ˜… Answer: 3 โœ“
05
Section Five ยท Implementation

Code โ€” Java & Python

Java โ€” Recursive DFS
class Solution { public int maxDepth(TreeNode root) { if (root == null) return 0; return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); } }
Python โ€” Recursive DFS
class Solution: def maxDepth(self, root) -> int: if not root: return 0 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
06
Section Six ยท Analysis

Complexity Analysis

ApproachTimeSpace
Recursive DFSO(n)O(h) โ€” call stack
Iterative BFSO(n)O(n) โ€” queue
07
Section Seven ยท Edge Cases

Edge Cases & Pitfalls

CaseInputWhy It Matters
EmptynullDepth = 0.
Single node[1]Depth = 1.
Skewed1โ†’2โ†’3โ†’4Depth = 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.

โ† Back to Trees problems