InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Maximum Depth of Binary Tree

easy Original ↗ 00:00

Problem

Given the root of a binary tree, return its maximum depth: the number of nodes on the longest path from the root down to any leaf. An empty tree has depth 0; a single node has depth 1.

Examples

Example 1

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

        3
       / \
      9  20
        /  \
       15   7

Output: 3

The longest root-to-leaf paths (3→20→15, 3→20→7) contain 3 nodes.

Example 2

Input:  root = [1,null,2]
Output: 2

The only path is 1 → 2.

Example 3

Input:  root = []
Output: 0

No nodes, depth 0.

Constraints

  • The number of nodes is in [0, 10^4] — a single O(n) traversal is expected.
  • -100 <= Node.val <= 100 — only the tree’s shape matters, not the values.

Think about it first

Hint 1 If someone handed you the depths of the left subtree and the right subtree, how would you get the depth of the whole tree?
Hint 2 `depth(node) = 1 + max(depth(node.left), depth(node.right))`, with `depth(None) = 0`. That is a complete algorithm.
Hint 3 Two classic non-recursive versions: BFS counting how many levels you peel off, or DFS with a stack of `(node, depth)` pairs. Know one for the "no recursion" follow-up.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug