codebrew.ai

Maximum Depth of Binary Tree

A node's depth is one more than its deeper subtree.

Approach

Recurse: the depth of a node is 1 + max(depth(left), depth(right)), with null contributing 0. A BFS level count works too. Both visit every node once.

Time complexity

O(n)

Space complexity

O(h)

Common mistake

Off-by-one at the base case — a null child is depth 0, a leaf is depth 1.

See it run, step by step

Generate an interactive lesson for Maximum Depth of Binary Tree — trace every variable and watch the algorithm execute until it clicks.

Start a lesson on Maximum Depth of Binary Tree

Related problems