1. Empty is zero
A missing subtree contributes no depth.
if (root === null) {
return 0;
}Typorithm · easy
Step 1 of 8 · intro card
Trees
Depth equals one plus the maximum depth of the two subtrees, with empty subtrees counting as zero.
The depth of a tree is the longest path from the root down to a leaf.
Each node adds one to the deeper of its two subtrees.
The base case — an empty subtree — has depth zero, anchoring the recursion.
Empty subtree depth is 0.
Take the max of both children.
Add 1 for the current node.
function maxDepth(root) {
if (root === null) {
return 0;
}
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}Connect each part of the code to the concept before you type.
A missing subtree contributes no depth.
if (root === null) {
return 0;
}Depth is driven by the taller subtree.
Math.max(maxDepth(root.left), maxDepth(root.right))Add one for the current node above its children.
1 + Math.maxRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.