Graph Theory37 sections · 1633 units
Open in Course

LeetCode 104 Maximum Depth of Binary Tree - Implementation

Coding it

Here is the solution:

function maxDepth(root):
    if root is null:
        return 0

    left = maxDepth(root.left)
    right = maxDepth(root.right)
    return 1 + max(left, right)

This is the simplest tree DP. You do not need extra arrays or global variables. The recursion stack handles everything. Each call returns an integer, and you combine results as you return.

This runs in O(n)O(n) time and uses O(h)O(h) space.