Maximum Depth of Binary Tree

Easy
BFS

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.

While this can be solved with DFS, the BFS approach counts the number of levels traversed, which directly gives us the depth.

Example 1

Input: root = [3,9,20,null,null,15,7]
Output: 3
Explanation: The tree has 3 levels: root (3), children (9, 20), grandchildren (15, 7).

Example 2

Input: root = [1,null,2]
Output: 2
Explanation: The tree has 2 levels: root (1) and its right child (2).

Constraints

  • The number of nodes in the tree is in the range [0, 10^4]
  • -100 <= Node.val <= 100
Show Hints (4)
Hint 1: BFS naturally processes nodes level by level.
Hint 2: Count how many levels you traverse before the queue becomes empty.
Hint 3: Each iteration of the outer while loop processes exactly one level.
Hint 4: The depth equals the number of levels traversed.
Loading editor...

Test Results

Click "Run" to execute your code against test cases

AI Tutor

Socratic guidance - I'll ask questions, not give answers

AI Tutor
Hello! I'm your AI tutor, here to guide you through this problem using the Socratic method. I won't give you direct answers, but I'll ask questions and provide hints to help you discover the solution yourself. What's your first instinct when you look at this problem? What approach comes to mind?