Problem Statement

Maximum Depth of Binary Tree

A binary tree is a structure that starts at one node called the root, and each node can point to up to two nodes below it, a left child and a right child. Picture a family tree drawn upside down, with the oldest at the top. Given the root of such a tree, return its maximum depth. The maximum depth is how many nodes you pass through on the longest path, starting at the root and walking straight down to the farthest leaf. A leaf is a node with no children, the very bottom of a branch.

easyTreeTreesTime: O(n) · Space: O(h)

Signals to notice

find deepest pathtree heightrecursive structure

Brute force first

BFS level by level, count levels — but uses more memory. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

Recursive DFS: depth = 1 + max(left depth, right depth). Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Trace it on root = [3,9,20,null,null,15,7] (3 → left 9, right 20; 20 → left 15, right 7)

maxDepth(9): node 9 is a leaf → left=maxDepth(null)=0, right=maxDepth(null)=0 → return 1+max(0,0)=1
maxDepth(15): leaf → 1+max(0,0)=1
maxDepth(7): leaf → 1+max(0,0)=1
maxDepth(20): left=maxDepth(15)=1, right=maxDepth(7)=1 → return 1+max(1,1)=2
maxDepth(3): left=maxDepth(9)=1, right=maxDepth(20)=2 → return 1+max(1,2)=3
answer = 3

What must stay true

The depth of a node is 1 plus the maximum depth of its children. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Shape of the loop

function maxDepth(node):
    if node is null: return 0
    left  = maxDepth(node.left)
    right = maxDepth(node.right)
    return 1 + max(left, right)

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Confusing depth vs height — depth of a null node is 0, not -1. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Trees Pattern