Q11: Maximum Depth of Binary Tree
Calculate the maximum depth (number of nodes along the longest path from root to leaf) of a binary tree recursively.
Tree Maximum Depth (DFS)
function maxDepth(root) {
if (root === null) return 0;
const leftDepth = maxDepth(root.left);
const rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}💡 Recursively measures the depth of left and right child subtrees and returns the greater depth plus 1 for the current root node.
Key Takeaways
- Depth equals
1 + max(depth(left), depth(right)). - Base case for null nodes returns depth 0.
Knowledge Check
What is the worst-case space complexity of recursive maxDepth on a completely skewed tree?