FrontendInterviews.dev

Loading problem…

96. Maximum Depth of Binary Tree

Easy•
Acceptance: 94.44%
•
🔓3/3 Pro unlocks today

You're building a feature that needs to calculate the maximum depth of a nested data structure or tree. This is useful for validating nested forms, calculating DOM tree depth, or analyzing hierarchical data.

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Requirements

1. Basic Functionality

  • Calculate maximum depth of binary tree
  • Depth is number of nodes from root to deepest leaf
  • Handle empty tree (return 0)
  • Handle single node (return 1)

Example Usage

// Tree:     3
//          / \
//         9   20
//            /  \
//           15   7
maxDepth(root); // 3

// Tree: 1
maxDepth(root); // 1

// Tree: null
maxDepth(null); // 0

Real-World Context

This problem models real frontend scenarios:

  • DOM tree depth: Calculate maximum nesting level
  • Nested form validation: Check maximum nesting depth
  • Tree visualization: Determine tree height for rendering
  • Data structure analysis: Analyze hierarchical data depth

Constraints

  • The number of nodes in the tree is in the range [0, 10^4]
  • -100 <= Node.val <= 100
  • Empty tree has depth 0
  • Single node has depth 1