Editorial solutions and visualizations are prepared with care, but we do not guarantee 100% accuracy or completeness. Please use your own judgment to verify results. Visucodize is not responsible for decisions made based on this content.
Solution code
constCURRENT='current',CURRENT_COLOR='blue';constDONE='done',DONE_COLOR='green';constIN_PROGRESS='in_progress',IN_PROGRESS_COLOR='gold';functionvisMainFunction(treeData){initClassProperties();explanationAndColorSchemaNotifications();const root =convertInputToTree(treeData);const tree =newVisBinaryTree(root,{dataPropName:'val'});const depth =maxDepth(root, tree);notification(`π <b>Finished:</b> Maximum depth of this tree is <b>${depth}</b>.`);return depth;}functionmaxDepth(node, tree){if(!node){notification(`Reached a <b>null</b> node β depth is 0.`);return0;}startPartialBatch();setAsCurrentNode(node, tree);notification(`π΅ Visiting the ${makeColoredSpan('current node',CURRENT_COLOR)}. Calculating the depth of its left subtree.`);const nodeVM = tree.makeVisManagerForNode(node);
nodeVM.addClass(IN_PROGRESS);endBatch();const leftDepth =maxDepth(node.left, tree);startPartialBatch();setAsCurrentNode(node, tree);notification(`β¬ οΈ Completed calculation of left subtree depth: ${leftDepth} for the ${makeColoredSpan('current node',CURRENT_COLOR)}. Now calculating the depth of its right subtree.`);endBatch();const rightDepth =maxDepth(node.right, tree);startPartialBatch();setAsCurrentNode(node, tree);const maxDepthAtNode = Math.max(leftDepth, rightDepth)+1;notification(`
β‘οΈ Completed calculation of the right subtree depth for the ${makeColoredSpan('current node',CURRENT_COLOR)}: ${rightDepth}.
<br>
π Maximum depth at this node = max(${leftDepth} (leftDepth), ${rightDepth} (rightDepth)) + 1 = <b>${maxDepthAtNode}</b>.
`);
nodeVM.removeClass(IN_PROGRESS);
node.val =`D: ${maxDepthAtNode}`;// Note that the original algorithm update does not update the value here but it is needed to show the calculated depth of the node for visualization purposes
nodeVM.addClass(DONE);endBatch();return maxDepthAtNode;}let currentNode =null;functionsetAsCurrentNode(node, tree){if(!node || node === currentNode)return;
currentNode && tree.makeVisManagerForNode(currentNode).removeClass(CURRENT);
tree.makeVisManagerForNode(node).addClass(CURRENT);
currentNode = node;}functioninitClassProperties(){setClassProperties(IN_PROGRESS,{backgroundColor:IN_PROGRESS_COLOR});setClassProperties(DONE,{backgroundColor:DONE_COLOR});setClassProperties(CURRENT,{borderColor:CURRENT_COLOR});}functionconvertInputToTree(arr){if(!arr.length || arr[0]===null)returnnull;const nodes = arr.map(val=>(val ===null?null:newTreeNode(val)));for(let i =0; i < arr.length; i++){if(nodes[i]){
nodes[i].left = nodes[2* i +1]||null;
nodes[i].right = nodes[2* i +2]||null;}}return nodes[0];}functionTreeNode(val, left =null, right =null){this.val = val;this.left = left;this.right = right;}functionexplanationAndColorSchemaNotifications(){explanationNotification();notification(`
π¨ <b>Visual Cues:</b>
<ul>
<li>${makeColoredSpan('Current node',CURRENT_COLOR)}: blue border</li>
<li>${makeColoredSpan('Visited/In-progress node',IN_PROGRESS_COLOR)}: gold background</li>
<li>${makeColoredSpan('Completed node',DONE_COLOR)}: node whose maximum depth has been fully computed (green background). The node label is updated to <code>D: <i>depth</i></code>, where <i>depth</i> is the calculated depth at that node.</li>
</ul>
`);}
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.
Input-1
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.