Practice

Maximum Depth of Binary Tree

Module 17 · Binary Trees

Problem

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.

Examples

Example 1

Inputroot = [3,9,20,null,null,15,7]Output3

Explanation. longest root-to-leaf: 3-20-15 or 3-20-7

Example 2

Inputroot = []Output0

Explanation. empty tree

Example 3

Inputroot = [1,null,2]Output2

Explanation. path 1-2

text
      3
     / \
    9   20
       /  \
      15   7

Constraints

0 ≤ n ≤ 10⁴ nodes · node values fit in a machine int

Attempt it first

This is the warm-up for the whole module, and it is deliberately the cleanest possible instance of bottom-up recursion from the previous lesson. Before revealing anything, write it: decide what an empty subtree returns, decide how a node combines its two children's answers into its own. If you internalize this one, maximum depth becomes the template you pattern-match every harder tree problem against.