#104

Maximum Depth of Binary Tree

EasyTreeHas vizTreeDFSBFS
Related studio

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.

Example 1

Input: root = [3,9,20,null,null,15,7]

Output: 3

Longest root-to-leaf path has 3 nodes.

Example 2

Input: root = [1,null,2]

Output: 2

Root and one child.

Constraints

  • The number of nodes in the tree is in the range [0, 10^4].
  • -100 <= Node.val <= 100
Loading visualization…

Explanation

Maximum Depth of Binary Tree is a Easy interview problem tagged [Tree, DFS, BFS]. The winning approach is typically **Tree**.

Intuition

Tree problems factor into identical subproblems on subtrees.

Approach

Recurse on left/right (DFS) or process level-by-level with a queue (BFS).

  1. Define base case (null).
  2. Ask what left/right return.
  3. Combine into the node answer.
  4. Watch stack depth on skewed trees.

Solution

Pattern-level skeleton only — not this problem’s exact answer. Adapt it to the statement.

Pattern templateTree

Edge cases

  • •Empty or single-element input
  • •Duplicates and ties
  • •Maximum constraints / overflow
  • •Disconnected or unreachable states (for graphs)

Complexity

Time: O(n)

Space: O(1)

Before coding, restate the problem, name the pattern (Tree), and write the invariant or DP state in one sentence.

Learn the topic

Got it?

Mark #104 Maximum Depth of Binary Tree as understood when the pattern clicks.