Pattern visualizer
Maximum Depth of a Binary Tree
Depth is defined in terms of itself: a node's depth is 1 plus the deeper of its two children. That makes recursion the natural fit — each call waits on its children, and the answer climbs back up the call stack. Animated on: Return the number of nodes along the longest path from the root down to the farthest leaf, for the tree [3, 9, 20, null, null, 15, 7]..
Binary Trees
step 1 / 12
9
3
15
20
7
Call stack
maxDepth(3)
line 1
Call maxDepth(3). To answer for the root we first need the depths of its two children — so we go down before we can come back up.
Pseudocode
1FUNCTION maxDepth(node):2 IF node is null: RETURN 03 left = maxDepth(node.left)4 right = maxDepth(node.right)5 RETURN 1 + the larger of left and right6END FUNCTION
← / → step · space play · Home restart