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

Input: root = [3,9,20,null,null,15,7]
Output: 3
Input: root = [1,null,2]
Output: 2
Constraints:

Contents

Recursive DFS

The depth of a tree is 1 + the maximum depth of its left and right subtrees. This leads to a clean one-line recursive solution.

Algorithm:
public int maxDepth(TreeNode root) { if (root == null) return 0; int leftDepth = maxDepth(root.left); int rightDepth = maxDepth(root.right); return 1 + Math.max(leftDepth, rightDepth); }
Complexity:
Iterative BFS (Level-Order)

Process the tree level by level with a queue. Each iteration of the outer loop represents one complete level — count the levels.

public int maxDepth(TreeNode root) { if (root == null) return 0; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); int depth = 0; while (!queue.isEmpty()) { int levelSize = queue.size(); // nodes at current level depth++; for (int i = 0; i < levelSize; i++) { TreeNode node = queue.poll(); if (node.left != null) queue.offer(node.left); if (node.right != null) queue.offer(node.right); } } return depth; }
Complexity:
ApproachTimeSpace
Recursive DFSO(n)O(h) — call stack
Iterative BFSO(n)O(n) — queue
For this problem both approaches are O(n) time. DFS is preferred for its simplicity and O(h) space on balanced trees.