Maximum Depth of Binary Tree - Problem

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.

Input & Output

Example 1 — Balanced Tree
$ Input: root = [3,9,20,null,null,15,7]
Output: 3
💡 Note: The longest path is from root 3 → 20 → 15 (or 7), which has 3 nodes, so depth is 3.
Example 2 — Linear Tree
$ Input: root = [1,null,2]
Output: 2
💡 Note: The tree has only a right path: 1 → 2, so the depth is 2.
Example 3 — Single Node
$ Input: root = [1]
Output: 1
💡 Note: Tree has only one node (the root), so the depth is 1.

Constraints

  • The number of nodes in the tree is in the range [0, 104]
  • -100 ≤ Node.val ≤ 100

Visualization

Tap to expand
Maximum Depth: Count Longest Path from Root to Leaf3Root (Level 1)9Level 220Level 215Level 37Level 3Path 1: 3→9 (depth=2)Path 2: 3→20→7 (depth=3)Longest: 3→20→15 (depth=3)All Paths:• 3 → 9 (depth = 2)• 3 → 20 → 15 (depth = 3)• 3 → 20 → 7 (depth = 3)Maximum Depth = 3Output: 3
Understanding the Visualization
1
Input Tree
Binary tree with nodes at different levels
2
Find Paths
Identify all root-to-leaf paths
3
Count Levels
Return the maximum number of levels (nodes in longest path)
Key Takeaway
🎯 Key Insight: Tree depth equals 1 + maximum depth of subtrees
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
235.8K Views
High Frequency
~15 min Avg. Time
8.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen