Skip to problem
←

Maximum Depth of Binary Tree

Easy 0 attempts

You're given the root of a binary tree. Return its maximum depth — the count of nodes along the longest path starting at the root and ending at whichever leaf is farthest away.

A leaf has no children. Count nodes, not edges: an empty tree has depth 0, and a single-node tree has depth 1. Node values do not affect the answer.

In Example 1, a longest path is 3 → 20 → 15, containing three nodes, so the depth is 3.

Function contract

Implement maximumDepthOfBinaryTree(root). Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.

Output: Return the maximum number of nodes on a root-to-leaf path. Return 0 for an empty tree.

Example 1

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

Example 2

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

Example 3

Input
root = []
Output
0
Constraints
  • 0 <= number of nodes <= 10^4
  • -100 <= Node.val <= 100

Iterative DFS

Track each node with its depth. An explicit stack also works for a long chain without overflowing the JavaScript call stack.

javascript
function maximumDepthOfBinaryTree(root) {
  if (!root) return 0;
  const stack = [[root, 1]];
  let depth = 0;
  while (stack.length) {
    const [node, d] = stack.pop();
    depth = Math.max(depth, d);
    if (node.left) stack.push([node.left, d + 1]);
    if (node.right) stack.push([node.right, d + 1]);
  }
  return depth;
}

Time: O(n) | Space: O(h) auxiliary space, excluding output

Loading discussion…

Saved in this browser only. Private to you.

JavaScript