Data Structures19 sections · 729 units
Open in Course

Max Depth Solution

The recursive formula

The recursive insight: the depth of a tree equals 1 plus the maximum depth of its subtrees.

function maxDepth(root):
    if root == null:
        return 0
    leftDepth = maxDepth(root.left)
    rightDepth = maxDepth(root.right)
    return 1 + max(leftDepth, rightDepth)

Base case: null node has depth 0.

Recursive case: depth is 1 (for current node) plus the deeper subtree.

Time: O(n)O(n). Visit each node once.

Space: O(h)O(h). Recursion depth equals tree height.

This three-line solution captures the essence of recursive tree thinking. Many harder problems are variations of this pattern.