Maximum Depth of Binary Tree

Easy
DFS

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.

Example Tree:

    3
   / \
  9  20
    /  \
   15   7

Maximum depth: 3 (path: 3 -> 20 -> 15 or 3 -> 20 -> 7)

This is a classic DFS problem where we explore each path to its deepest point and track the maximum depth encountered.

Approach:

  • Base case: If node is null, depth is 0
  • Recursive case: depth = 1 + max(leftDepth, rightDepth)

Example 1

Input: root = [3,9,20,null,null,15,7]
Output: 3
Explanation: The deepest path is 3 -> 20 -> 15 (or 3 -> 20 -> 7), which has 3 nodes.

Example 2

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

Example 3

Input: root = []
Output: 0
Explanation: An empty tree has depth 0.

Constraints

  • The number of nodes in the tree is in the range [0, 10^4].
  • -100 <= Node.val <= 100
Show Hints (4)
Hint 1: What is the depth of an empty tree? What is the depth of a single node?
Hint 2: The depth at any node is 1 plus the maximum depth of its subtrees.
Hint 3: DFS naturally explores depth-first, making this problem straightforward.
Hint 4: Can you also solve this with BFS by counting levels?
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?