DSA AnimatorDSA animations
Maximum Depth of Binary Tree LC #104 Easy DFS · Post-order
Problem

Given the root of a binary tree, return its maximum depth — the number of nodes along the longest path from the root node down to the farthest leaf node.

Example 1
Input: root = [3,9,20,null,null,15,7]
Output: 3
Explanation: Deepest path: 3 → 20 → 15 (or 7), length 3.
Example 2
Input: root = [1,null,2]
Output: 2
Constraints: 0 ≤ nodes ≤ 104  |  −100 ≤ Node.val ≤ 100
Try Examples
Custom:
Approach
DFS Post-order Recursion
Recurse left and right subtrees first, then combine: depth = 1 + max(leftDepth, rightDepth). Base case: null node returns 0. The answer propagates back up the call stack.
Binary Tree
Processing
Returning
Done
Unvisited
Recursion Stack
Stack is empty — not started
Depth Return Values
No values returned yet…
Variables
Current Node
—
Left Depth
—
Right Depth
—
Max Depth
—
Call Trace
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Base case: root == null → return 0 (null node has depth 0)
2
Recurse left: L = maxDepth(root.left)
3
Recurse right: R = maxDepth(root.right)
4
Return 1 + Math.max(L, R) — this node adds 1 to the deeper subtree
Time
O(n)
Space
O(h)
Why Post-order Works

Post-order (left → right → root) processes children before the parent. By the time we ask "what is the depth of this node?", both subtree depths are already known. The depth of any node is simply 1 (for itself) + the deeper of its two subtrees. This naturally bubbles the answer up from leaves (depth 1) to the root. The call stack is the recursion — as it unwinds, values propagate back up.

How to solve Maximum Depth of Binary Tree

LeetCode 104 · Easy · Tree · Pattern: DFS Height

Why the obvious approach is slow

You could list every root to leaf path and take the longest one. But storing every path is unnecessary, because only the length matters.

The key idea

The depth of a tree is 1 for the root, plus the deeper of its two subtrees. An empty tree has depth 0, and that is the base case. So the recursion asks each child for its depth, and passes the answer up.

Remember

Depth equals 1 plus the deeper child. Counting levels with a breadth first search gives the same answer.

Run the animation above on your own input, or watch the 1:36 video explanation of Maximum Depth of Binary Tree with a dry run and Java code.

More Tree problems