Blind 75 · Trees

Maximum Depth of Binary Tree

Easy

Watch the walkthrough (4:57)

Problem

The input is root, the root of a binary tree.
A path goes from the root down to a leaf, a node with no children.
The maximum depth is the number of nodes on the tree's longest path.
Return the maximum depth; an empty tree has a depth of 0.

Examples

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

Example 2:
Input: root = [1,null,2]
Output: 2

Example 3:
Input: root = []
Output: 0

Example 4:
Input: root = [1]
Output: 1

Constraints

0 <= number of nodes <= 10^4
-100 <= Node.val <= 100

Prerequisites

Binary trees, and recursion over them: solve the children, combine, return. The base case is almost always the empty tree.
Depth-first order (pre, in, post) and breadth-first by level — and knowing which one a problem is really asking for.

How to think about it

1. One Plus the Deeper Child Optimal

Intuition

A tree's depth is one more than its deepest subtree, and an empty tree has none. That sentence is the whole solution — the value here is checking that recursion over trees feels natural, because everything else in this section assumes it does.

Algorithm

1. Empty tree: 0.
2. Otherwise: 1 plus the larger of the two subtree depths.

Time & Space

Time O(n). Space O(h) for the stack; a level-order walk trades it for a queue of the widest level.

2. One Expression

Intuition

The same recursion, written as one expression: the two calls go straight into max, and neither depth is named. It reads the way the definition does. Naming the two depths, as the first approach does, puts each on a line of its own, which is easier to follow in a walkthrough and to stop on in a debugger; the work is the same.

Algorithm

1. Empty tree: 0.
2. Otherwise: 1 plus the larger of the two subtree depths.

Time & Space

Time O(n). Space O(h) for the stack; a level-order walk trades it for a queue of the widest level.