Maximum Depth of Binary Tree - JS Solution

JS
Editorial

Solution explanation

Solution explanation

Approach

πŸ’‘ Intuation

We use a Depth-First Search (DFS) recursion to compute the maximum depth (height) of the binary tree. The idea is simple yet powerful: the depth of any valid node is 1 more than the maximum depth of its left and right subtrees. A null root or child represents an empty branch with a height of 0.

🌿 Base Case

If the current node is null, we have reached beyond a leaf β€” return 0.

🌳 Recursive Step

  • Recursively compute the depth of the left subtree.
  • Recursively compute the depth of the right subtree.
  • Return 1 + max(leftDepth, rightDepth) to include the current node’s level.

πŸ” Traversal Logic

This approach explores all nodes exactly once. Each node contributes to the total depth through its recursive return value.

Time Complexity

O(n), where n is the number of nodes β€” each node is visited exactly once.

Space Complexity

O(h) β€” where h is the recursion stack depth proportional to the height of the tree. In the worst case (a completely skewed tree), this becomes O(n); for a balanced tree, it is O(log n), where n is the number of nodes in the tree.

Visucodize editorial solution titled JS Solution for LeetCode's Maximum Depth of Binary Tree coding problem. Includes code and may include explanation. You can animate the code step by step using the provided input by clicking the run button, or fork it locally to update the code and input for custom visualization. View the original problem at https://leetcode.com/problems/maximum-depth-of-binary-tree.