Skip to content

Maximum Depth of Binary Tree

EasyLeetCode #104Time O(n)Space O(h)

You get the root of a binary tree. Return its maximum depth: the number of nodes along the longest path from the root down to the farthest leaf. An empty tree has depth 0.

[3, 9, 20, null, null, 15, 7] -> 3 (3 -> 20 -> 15)

You can’t read the depth off a single node, but you can if you already know the depth of each child. The tree’s depth is one (for the root itself) plus the larger of the left subtree’s depth and the right subtree’s depth.

That is the whole recursion: ask each side for its depth, take the max, add 1. The empty tree returns 0, which is the base case that stops the recursion. This “answer for a node = combine the answers for its children” shape is the template for most tree problems.

Show solutionHide solution
def max_depth(root: TreeNode | None) -> int:
if root is None:
return 0
# Depth = this node + the deeper of the two subtrees.
return 1 + max(max_depth(root.left), max_depth(root.right))
  • Time: O(n) — every node is visited exactly once.
  • Space: O(h) — recursion stack of height h: O(log n) if balanced, O(n) if the tree is a single chain.
  • Count nodes, not edges. LeetCode defines depth as nodes on the path, so a single node has depth 1 and None has depth 0.
  • Don’t confuse it with minimum depth. The minimum is not 1 + min(left, right); see the variation below.
  • Deep chains can overflow the stack in Python (default limit about 1000). LeetCode’s inputs are fine; in an interview, mention an iterative BFS as the fallback.

Minimum Depth of Binary Tree (LeetCode 111)

Section titled “Minimum Depth of Binary Tree (LeetCode 111)”

Shortest path from the root to a leaf. The trick: if a node has only one child, you must follow that child; the missing side is not a leaf, so min with 0 would be wrong. Only take min when both children exist.

Is every node’s left and right height within 1 of each other? The trick: compute heights bottom-up and return a sentinel such as -1 as soon as any subtree is unbalanced, so the whole check is one O(n) pass instead of recomputing heights.

Longest path between any two nodes, in edges. The trick: it is the same depth recursion, but at each node update a global best with left_depth + right_depth before returning 1 + max(left, right).