Maximum Depth of Binary Tree

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.

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

Contents

Solution 1: 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:
Java
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:

Solution 2: 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.

Java
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:

Complexity Analysis

ApproachTimeSpace
Recursive DFSO(n)O(h): call stack
Iterative BFSO(n)O(n): queue

Note: For this problem both approaches are O(n) time. DFS is preferred for its simplicity and O(h) space on balanced trees.