Binary Tree Maximum DepthLoading saved progress…

Binary Tree Maximum Depth

You're given the root of a binary tree — a structure where every node has at most two children, left and right. The maximum depth is the count of nodes along the longest path from the root down to any leaf (a node with no children). A folder tree, a comment thread, an HTML DOM — all are binary or n-ary trees, and "how deep does this go?" is a question you'll answer often.

Implement binaryTreeMaximumDepth(root). The root is either a node of shape { val, left, right } or null. Each child is itself either a node of the same shape or null. Return the depth as a non-negative integer.

Signature

// node shape: { val: any, left: Node | null, right: Node | null }
function binaryTreeMaximumDepth(root) {
  // returns the number of nodes on the longest root-to-leaf path,
  // or 0 if root is null.
}

Examples

// A single node — depth 1.
binaryTreeMaximumDepth({ val: 1, left: null, right: null }); // 1

// A balanced tree of three nodes — depth 2.
//        1
//       / \
//      2   3
binaryTreeMaximumDepth({
  val: 1,
  left:  { val: 2, left: null, right: null },
  right: { val: 3, left: null, right: null },
}); // 2
// A lopsided tree — longest path is on the left.
//        1
//       /
//      2
//     /
//    3
binaryTreeMaximumDepth({
  val: 1,
  left: {
    val: 2,
    left:  { val: 3, left: null, right: null },
    right: null,
  },
  right: null,
}); // 3

// An empty tree.
binaryTreeMaximumDepth(null); // 0

Notes

  • Empty tree — when root is null, return 0. A non-existent tree has zero depth.
  • Single node — a root with no children has depth 1, not 0. The root itself counts.
  • Lopsided trees — the answer is 1 + max(depth(left), depth(right)). Don't average; don't pick the shallower side.
  • Don't mutate the input tree. This is a read-only traversal.
  • Don't worry about extremely deep trees blowing the call stack — inputs in tests stay under a few thousand nodes.
Loading editor…