Algorithms and Data Structures · Middle · Question 38 of 75
How do you compute the maximum depth of a binary tree recursively?
function depth(node) {
if (!node) return 0;
// ?
}- 1
return depth(node.left) + depth(node.right); - ✓Correct answer:
return 1 + Math.max(depth(node.left), depth(node.right)); - 3
return 1 + Math.min(depth(node.left), depth(node.right));
Explanation
The depth of a node is one more than the deeper of its subtrees, and an empty subtree has depth 0. Adding both subtrees would count nodes, not depth. The cost is O(n), with recursion depth equal to the height.