Visualize

Pattern visualizer

Binary Tree Postorder Traversal

Postorder is bottom-up: a node may only report after BOTH of its subtrees are completely done, so leaves go first and the root goes last. Watch the call stack — every frame waits for the frames above it before it appends its own value. Animated on: Return the postorder traversal of the tree [1, 2, 3, 4, 5, null, 6] — expected [4,5,2,6,3,1]..

Left, right, then self

time O(n)space O(h)step 1 / 9
4
2
5
1
3
6

Call stack

postorder(1)
line 4

Enter postorder(1). Its value is NOT appended yet: postorder means both subtrees (2 and 3) must be completely finished first, so this frame parks on the stack and recurses left.

Pseudocode
1FUNCTION postorder(node, out):
2 IF node = null:
3 RETURN
4 postorder(node.left, out)
5 postorder(node.right, out)
6 APPEND node.val TO out
7 RETURN out

← / → step · space play · Home restart

Where to practice Binary Trees