Step by step · Python and Java

Maximum depth of a binary tree, visualized

Finding the depth of a binary tree (LeetCode 104) is the cleanest example of a recursive function that builds its answer on the way back up.

How it works
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None


def insert(node, val):
    if node is None:
        return TreeNode(val)
    if val < node.val:
        node.left = insert(node.left, val)
    else:
        node.right = insert(node.right, val)
    return node


def max_depth(node):
    # An empty subtree has depth 0: the base case every other answer builds on.
    if node is None:
        return 0
    left = max_depth(node.left)
    right = max_depth(node.right)
    return 1 + max(left, right)


root = None
for value in [50, 30, 70, 20, 40, 80, 10]:
    root = insert(root, value)

print(max_depth(root))

How the maximum-depth recursion works

The depth of an empty tree is 0. The depth of any other node is 1 plus the larger of its two subtrees’ depths. So the function calls itself on the left child, then on the right child, and only once both have returned can it compute its own answer.

The Python example builds a tree from 50, 30, 70, 20, 40, 80, 10 and returns 4 — the path 50 → 30 → 20 → 10. The Java version is a LeetCode solution exactly as you would submit it, with no main method; the visualizer supplies the TreeNode class and a sample tree so it runs as written.

What to watch for when it runs

  1. The call stack holds one frame per node on the current path from the root.
  2. Each node’s depth is drawn travelling back up to its parent as the call returns.
  3. Null children return 0 straight away — the base case every other answer is built on.

Time and space complexity

Time
O(n)
Space
O(h)

Every node is visited once. The stack is as deep as the tree is tall: O(log n) when balanced, O(n) when it degenerates into a chain.

Stuck on your own version?

Paste it into the visualizer and watch your own code run, line by line — bugs included.