AlgoFrames

Max depth

Standard · Write code · about 8 min

Given the root of a binary tree, return its maximum depth: the number of nodes on the longest path from the root down to a leaf. An empty tree has depth 0.

Example 1

Input:

[[3,9,20,null,null,15,7]]

Output:

3

The longest paths are 3 → 20 → 15 and 3 → 20 → 7, with 3 nodes each.

Example 2

Input:

[[1,null,2]]

Output:

2

Constraints

  • 0 ≤ number of nodes ≤ 1,000
  • -1,000 ≤ Node.val ≤ 1,000
  • The tree is given in level order; null marks a missing child

Learn the idea first: Recursive problems on trees: height, size, mirror, paths, a visual lesson.

More Recursive problems on trees: height, size, mirror, paths problems