Skip to content

Maximum Depth of Binary Tree

Given the root of a binary tree, return its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

InputOutputExplanation
[3,9,20,null,null,15,7]3Tree has height 3: root → 9, root → 20 → 15/7
[1,null,2]2Unbalanced tree: root → right child
[]0Empty tree
Example 1: 3 Depth: 3
/ \
9 20
/ \
15 7
Example 2: 1 Depth: 2
\
2
Example 3: (empty) Depth: 0
  • The number of nodes in the tree is in the range [0, 10^4].
  • -100 <= Node.val <= 100
ApproachTimeSpaceBest When
DFS RecursiveO(n)O(h)Small to medium trees; simple code preferred
BFS Level-OrderO(n)O(w)Early termination possible; breadth matters

Where h = height (at most n), w = max width (at most n)

  • Pick DFS Recursive if you want the simplest, most elegant solution. It’s the natural way to think about the problem.
  • Pick BFS Level-Order if you want to understand tree level-by-level traversal or need to optimize for specific tree shapes.
Simplest
DFS Recursive
O(n) time · O(h) space
Level-by-Level
BFS Level-Order
O(n) time · O(w) space
★ Recommended

For each node, recursively find the maximum depth of its left and right subtrees, then return 1 plus the maximum of those two depths.

The insight is simple: the depth of a tree is 1 plus the depth of its taller subtree. For a null node, the depth is 0.

⏱ Time O(n) Visit all nodes once 💾 Space O(h) Recursion call stack

Input: root = [3,9,20,null,null,15,7]

3
/ \
9 20
/ \
15 7
NodeLeft Subtree DepthRight Subtree DepthResult
15001 + max(0, 0) = 1
7001 + max(0, 0) = 1
9001 + max(0, 0) = 1
20111 + max(1, 1) = 2
3121 + max(1, 2) = 3

Animated walkthrough

How DFS recursion finds the maximum depth

Use Next or Autoplay to watch as the recursion explores left subtree, right subtree, then combines results at each node.

Step 1 of 5
Waiting to begin...
Array state
Memory / lookup state

function maxDepthDFS(root):
if root is null:
return 0
leftDepth = maxDepthDFS(root.left)
rightDepth = maxDepthDFS(root.right)
return 1 + max(leftDepth, rightDepth)
maximum_depth_of_binary_tree_dfs.py
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def maxDepth(root: Optional[TreeNode]) -> int:
"""
Find the maximum depth of a binary tree using DFS (recursive).
Time Complexity: O(n) where n is the number of nodes
Space Complexity: O(h) where h is the height (call stack depth)
"""
if root is None:
return 0
return 1 + max(maxDepth(root.left), maxDepth(root.right))
# Test cases
if __name__ == "__main__":
# Example 1: [3,9,20,null,null,15,7]
# 3
# / \
# 9 20
# / \
# 15 7
root1 = TreeNode(3)
root1.left = TreeNode(9)
root1.right = TreeNode(20)
root1.right.left = TreeNode(15)
root1.right.right = TreeNode(7)
print(maxDepth(root1)) # Expected: 3
# Example 2: [1,null,2]
# 1
# \
# 2
root2 = TreeNode(1)
root2.right = TreeNode(2)
print(maxDepth(root2)) # Expected: 2
# Example 3: Empty tree
root3 = None
print(maxDepth(root3)) # Expected: 0
🎯 Interview Favourite

Use a queue to traverse the tree level by level. Increment the depth counter after processing each complete level. Return the depth when the queue becomes empty.

This approach processes nodes layer by layer, which can be more intuitive for understanding tree structure and is useful when you need information about each level.

⏱ Time O(n) Visit all nodes once 💾 Space O(w) Queue width at widest level

Input: root = [3,9,20,null,null,15,7]

3 Level 1: process [3], depth = 1
/ \
9 20 Level 2: process [9, 20], depth = 2
/ \
15 7 Level 3: process [15, 7], depth = 3
StepCurrent LevelQueue AfterDepth
1[3][9, 20]1
2[9, 20][15, 7]2
3[15, 7][]3
4Queue emptyReturn 3 ✓
function maxDepthBFS(root):
if root is null:
return 0
queue = [root]
depth = 0
while queue is not empty:
depth += 1
levelSize = length of queue
for i = 0 to levelSize - 1:
node = queue.dequeue()
if node.left exists:
queue.enqueue(node.left)
if node.right exists:
queue.enqueue(node.right)
return depth
maximum_depth_of_binary_tree_bfs.py
from typing import Optional
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def maxDepth(root: Optional[TreeNode]) -> int:
"""
Find the maximum depth of a binary tree using BFS (level-order traversal).
Time Complexity: O(n) where n is the number of nodes
Space Complexity: O(w) where w is the maximum width of the tree
"""
if root is None:
return 0
queue = deque([root])
depth = 0
while queue:
depth += 1
# Process all nodes at the current level
for _ in range(len(queue)):
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return depth
# Test cases
if __name__ == "__main__":
# Example 1: [3,9,20,null,null,15,7]
# 3
# / \
# 9 20
# / \
# 15 7
root1 = TreeNode(3)
root1.left = TreeNode(9)
root1.right = TreeNode(20)
root1.right.left = TreeNode(15)
root1.right.right = TreeNode(7)
print(maxDepth(root1)) # Expected: 3
# Example 2: [1,null,2]
# 1
# \
# 2
root2 = TreeNode(1)
root2.right = TreeNode(2)
print(maxDepth(root2)) # Expected: 2
# Example 3: Empty tree
root3 = None
print(maxDepth(root3)) # Expected: 0