Depth-First Search
Easy
Maximum Depth of Binary Tree
Find the maximum depth (height) of a binary tree.
10 min read
Solve on LeetCodeExamples
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.
- Base Case: If the node is
null, its depth is0. - Recursive Step:
- Ask the Left Child: "What is your max depth?"
- Ask the Right Child: "What is your max depth?"
- Calculation: My Depth =
max(left_depth, right_depth) + 1.
Interactive Visualization
Step 1 / 15
3
?
9
20
15
7
3
09
120
23
4
15
57
6At 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.ON THIS PAGE
- Problem Understanding
- Algorithm Strategy (Bottom-Up)
- Interactive Visualization
- Dry Run
- Edge Cases
- Solution
- Complexity Analysis
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.
