Coding problem · Easy · Trees

Maximum Depth of Binary Tree

Easy Algorithms & data structures Seen at Amazon, LinkedIn, Uber

Given the root of a binary tree, return its maximum depth — the number of nodes along the longest path from the root down to the farthest leaf. Trees are shown in level order with null for missing children.

Example 1

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

Example 2

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

Hints

Hint 1

depth(node) = 1 + max(depth(left), depth(right)); an empty tree has depth 0.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) · Space O(h) recursion depth

Recursive DFS returns 1 + max(left, right). For very deep (skewed) trees, an iterative BFS counting levels avoids stack overflow.

Reference solution

function maxDepth(root) {
  if (!root) return 0;
  return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}