← Back to DSA Animator
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.