Data Structures & Algorithms Binary Trees
💡
Exercise 89

Maximum Depth 15 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

Given a binary tree, find its maximum depth — the number of nodes along the longest path from root to the farthest leaf.

# 3 # / \ # 9 20 # / \ # 15 7 # Maximum depth = 3 (path: 3 → 20 → 15 or 3 → 20 → 7)

This is the simplest recursive tree problem — the hello world of tree recursion:

  • Base case: Empty node → depth is 0
  • Recursive case: 1 + max(depth of left, depth of right)
  • Time: O(n), Space: O(h) where h = height

This pattern — combine results from left and right subtrees — is the foundation of almost every tree problem.

📋 Instructions
Implement `max_depth(root)` recursively. Test with the tree above and an empty tree.
Recursion! Base case: if root is None, return 0. Otherwise: return 1 + max(depth(left), depth(right)). Think: depth = 1 (me) + the deeper subtree.
🧪 Test Cases
Input
max_depth(root)
Expected
3
Test case 1
Input
max_depth(None)
Expected
0
Edge case — null/empty input
Input
max_depth(TreeNode(1))
Expected
1
Test case 3
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.