Depth-First Search
Easy

Maximum Depth of Binary Tree

Find the maximum depth (height) of a binary tree.
Examples
Input:root = [3,9,20,null,null,15,7]
Output:3
Explain:

The tree has nodes 3 -> (9, 20). 20 -> (15, 7). The longest path is 3->20->15 (length 3).

Input:root = [1,null,2]
Output:2
Problem Understanding

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Algorithm Strategy (Bottom-Up)

We use Post-order DFS (Bottom-Up) to solve this.

  1. Base Case: If the node is null, its depth is 0.
  2. Recursive Step:
    • Ask the Left Child: "What is your max depth?"
    • Ask the Right Child: "What is your max depth?"
  3. Calculation: My Depth = max(left_depth, right_depth) + 1.
Interactive Visualization
Step 1 / 15
3
?
9
20
15
7
3
0
9
1
20
2
3
4
15
5
7
6

At Node 3. Asking children for their max depth.

1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.
Unlock VisualizerPREMIUM FEATURE

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.

Start Your Premium Prep