Skip to main content

Binary Tree Maximum Depth Finder

easy
TreeDepth First SearchBinary TreeRecursionDfs Recursive
Asked atAmazonGoogleMicrosoftMeta

Problem Description

Given the root of a binary tree, determine its **maximum depth** — the number of nodes along the longest path from the root down to the farthest leaf node.

A leaf is a node with no children.

**Example 1:**
```
5
/ \
3 8
/ \
1 4
```
Input: root = [5,3,8,1,4]
Output: 3
Explanation: The longest path is 5 → 3 → 1 (or 5 → 3 → 4), which has 3 nodes.

**Example 2:**
```
7
\
2
\
9
```
Input: root = [7,null,2,null,9]
Output: 3
Explanation: The only path is 7 → 2 → 9, which has depth 3.

Constraints

  • The number of nodes in the tree is in the range [0, 10^4].
  • Node values are integers in the range [-100, 100].
  • A null root represents an empty tree and has depth 0.

Follow-up

Can you solve this iteratively using a queue (BFS) instead of recursion, avoiding stack overflow for very deep trees?

Hints

Try the problem first. If you get stuck, you can reveal hints one at a time.

Solution

Leaderboard

No entries yet for python.

Be the first — submit an accepted solution.