ToolMight Logo
EasyTrees & BSTDepth-First Search (DFS)Breadth-First Search (BFS)Tree Recursion

Maximum Depth of Binary Tree

Compute the maximum depth (node count along longest root-to-leaf path) of a binary tree using recursive post-order DFS and iterative level-order BFS.

Optimal Time
O(n)
Optimal Space
O(h)
Primary Pattern
Depth-First Search (DFS)
Visualizer
Open Interactive View →

Problem Statement

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.

Examples & Constraints

Example 1
Input: root = [3, 9, 20, null, null, 15, 7]
Output: 3
Explanation: The longest root-to-leaf path is 3 -> 20 -> 15 (or 7), which contains 3 nodes.
Example 2
Input: root = []
Output: 0
Explanation: An empty tree has a maximum depth of 0.
Constraints
  • The number of nodes in the tree is in the range [0, 10^4].
  • -100 <= Node.val <= 100

Pattern Recognition & Core Invariant

How to Spot This Pattern

Tree properties aggregated along paths from leaves back to the root divide cleanly into 1 + f(left, right) recursion or level-by-level BFS queue sweeps.

Core Invariant

The maximum depth rooted at any non-null node equals 1 plus the larger maximum depth of its left and right subtrees, with null nodes contributing 0.

Solution Approaches & Complexity

ApproachTimeSpaceNotes
1. Recursive DFS (Divide & Conquer)Optimal
O(n)O(h)Recursively find the height of the left and right subtrees. The tree height is 1 + max(leftHeight, rightHeight).
2. Iterative Level-Order BFS (Queue)
O(n)O(w)Traverse nodes level by level using a FIFO queue, incrementing depth once per drained tree level.

1. Recursive DFS (Divide & Conquer)

Optimal
TimeO(n)
SpaceO(h)

Recursively find the height of the left and right subtrees. The tree height is 1 + max(leftHeight, rightHeight).

Time ComplexityO(n)

Every node in the binary tree of size N is visited exactly once.

Space ComplexityO(h)

Consumes memory on the call stack proportional to tree height H: O(log n) for a balanced tree, and O(n) for a completely skewed linked-list tree.

How It Works

The Bottom-Up Recurrence Relation

A tree problem can almost always be broken down into identical subproblems on its subtrees:

  1. Base Case: If root == null, an empty tree has height 0.
  2. Recursive Hypothesis:
  • Let leftDepth = maxDepth(root.left).
  • Let rightDepth = maxDepth(root.right).
  1. Combine Step:
  • The current node contributes 1 level of depth to whatever is the taller branch below it.
  • Return 1 + max(leftDepth, rightDepth).

Call Stack Lifecycle

Execution flows down to the leaf nodes first (post-order traversal: Left, Right, then Root). When the leaves return depth 1, their parents calculate 1 + 1 = 2, bubbling up heights to the root.

Step-by-Step Dry Run

Execution Trace·Step 1 of 4
1Root Node (3)

Inspect root (3). Delegate subtrees: maxDepth(9) and maxDepth(20).

State:root = 3 (waiting on children)
Strengths
  • +Extremely clean and concise code
  • +Natural divide-and-conquer recurrence structure
Trade-offs
  • -Risk of call stack overflow on deeply skewed trees (N >= 10,000)

Reference Implementation

Complete implementation for Recursive DFS (Divide & Conquer) in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def max_depth(root: TreeNode | None) -> int:
if not root:
return 0
left_depth = max_depth(root.left)
right_depth = max_depth(root.right)
return 1 + max(left_depth, right_depth)
if __name__ == "__main__":
# Tree: [3, 9, 20, null, null, 15, 7]
root = TreeNode(3)
root.left = TreeNode(9)
root.right = TreeNode(20, TreeNode(15), TreeNode(7))
print("Maximum Depth:", max_depth(root))

2. Iterative Level-Order BFS (Queue)

TimeO(n)
SpaceO(w)

Traverse nodes level by level using a FIFO queue, incrementing depth once per drained tree level.

Time ComplexityO(n)

Every node is enqueued and dequeued once.

Space ComplexityO(w)

Queue holds at most one full tree level of width w (O(n/2) = O(n) for complete trees, O(1) for skewed chains).

How It Works

Iterative Depth Counting Without Call-Stack Risk

On deeply skewed trees, recursion allocates O(n) call frames. An explicit FIFO queue processes each level horizontally instead:

  1. If root == null, return 0.
  2. Push root into queue and initialize depth = 0.
  3. While queue is not empty:
  • Record levelSize = queue.length (exact count of nodes at the current depth).
  • Pop levelSize nodes, pushing any non-null left and right children.
  • Increment depth++.
  1. Return depth.

Step-by-Step Dry Run

Execution Trace·Step 1 of 4
1Seed Level 1

Enqueue root (3). levelSize = 1.

State:queue = [3]depth = 0
Strengths
  • +Immune to stack overflow on degenerate skewed trees
  • +Uses only O(1) memory on linked-list-like trees
Trade-offs
  • -Holds up to N/2 pointers on the final level of a balanced binary tree

Reference Implementation

Complete implementation for Iterative Level-Order BFS (Queue) in Python, JavaScript, Java, C++, and C.

File: solution.py
Python
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 max_depth_bfs(root: TreeNode | None) -> int:
if not root:
return 0
queue = deque([root])
depth = 0
while queue:
for _ in range(len(queue)):
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
depth += 1
return depth
Interactive Visualizer

Trace Binary Search Tree mechanics in memory

Step through custom inputs in the Binary Search Tree visualizer to inspect pointer updates, array shifts, and call-stack state alongside Maximum Depth of Binary Tree.

Open Binary Search Tree visualizer

Frequently Asked Questions

What is the difference between tree depth and tree height?

Depth measures edges from root down to a node (depth(root) = 0), while height measures edges down to the farthest leaf. In interview prompts like LeetCode 104, 'maximum depth' counts nodes along the longest root-to-leaf path (1-indexed node count).

How does DFS memory compare with BFS memory here?

Recursive DFS uses O(h) stack space (O(log n) balanced, O(n) skewed). Iterative BFS uses O(w) queue space (O(n) at the bottom of a full tree, O(1) for skewed chains).

Can we adapt maximum depth to check whether a tree is height-balanced?

Yes. Keep the same post-order height recurrence and return a sentinel -1 early if abs(leftHeight - rightHeight) > 1, solving Balanced Binary Tree in O(n) time.

Edge Cases & Implementation Pitfalls

Boundary Test Cases to Verify

  • Empty tree (root === null) returns 0.
  • Single root node with null children returns 1.
  • Unbalanced or completely right-skewed chain of 10^4 nodes reaches O(n) DFS recursion depth, risking stack overflow in Python unless iterative BFS/DFS is used.

Common Bugs to Avoid

  • Returning -1 instead of 0 for null children when the specification counts nodes rather than edges.
  • Forgetting to snapshot levelSize before popping inside the BFS level loop, causing levels to merge and inflating depth.
  • Evaluating depth only when both children are non-null (which misbehaves in Minimum Depth variants).

Interview Follow-Up Variations

  • Minimum Depth of Binary Tree: beware of nodes with only one child (a null branch is NOT a leaf!).
  • Diameter of Binary Tree & Balanced Binary Tree: both compute subtree heights inside the same post-order recursion.
  • Iterative DFS using an explicit (node, currentDepth) stack.

Related Problems

All problems
EasyTrees & BST

Invert Binary Tree

Mirror a binary tree around its vertical axis by swapping left and right child pointers via recursive DFS or iterative level-order BFS.

Pattern: DFS Traversal
O(n) · O(h)
Solve
EasyDynamic Programming

Climbing Stairs

Count distinct ways to climb n stairs taking 1 or 2 steps at a time. Progress from top-down memoization to O(1)-space Fibonacci dynamic programming.

Pattern: Fibonacci Sequence
O(n) · O(1)
Solve
EasyTrees & BST

Subtree of Another Tree

Check whether subRoot matches an entire subtree of root in structure and values. Compare double-DFS tree matching against O(n + m) pre-order serialization + substring search.

Pattern: Tree Traversal DFS
O(n * m) · O(h)
Solve