Binary Tree Postorder Traversal
Left, right, then self
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.
Details
Animated on: Return the postorder traversal of the tree [1, 2, 3, 4, 5, null, 6] — expected [4,5,2,6,3,1].
Problem:Binary Tree Postorder TraversalEasy
Left, right, then self
step 1 / 9
Call stack
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.
1FUNCTION postorder(node, out):2 IF node = null:3 RETURN4 postorder(node.left, out)5 postorder(node.right, out)6 APPEND node.val TO out7 RETURN out
← / → step · space play · Home restart
Every step in words
Show all 9 steps
- 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.
- Enter postorder(2). Its value is NOT appended yet: postorder means both subtrees (4 and 5) must be completely finished first, so this frame parks on the stack and recurses left.
- postorder(4) is a leaf: both child calls hit null and return immediately, so 4 is appended as element #1 — out is now [4]. Its frame pops and control returns to postorder(2).
- postorder(5) is a leaf: both child calls hit null and return immediately, so 5 is appended as element #2 — out is now [4, 5]. Its frame pops and control returns to postorder(2).
- Both subtrees of 2 have reported, so 2 finally appends itself as #3: out is [4, 5, 2]. A parent always lands AFTER everything beneath it — that is the whole definition of postorder. Frame pops back to postorder(1).
- Enter postorder(3). Its left child is null, so that call returns at once with nothing to add; the only child to finish is 6. Node 3 itself still has to wait — out is [4, 5, 2] and stays that way until 6 is done.
- postorder(6) is a leaf: both child calls hit null and return immediately, so 6 is appended as element #4 — out is now [4, 5, 2, 6]. Its frame pops and control returns to postorder(3).
- Both subtrees of 3 have reported, so 3 finally appends itself as #5: out is [4, 5, 2, 6, 3]. A parent always lands AFTER everything beneath it — that is the whole definition of postorder. Frame pops back to postorder(1).
- The root 1 is the very last node to append (#6) because nothing can finish before its children do. The stack is empty and out is [4, 5, 2, 6, 3, 1].
Now solve it yourself
Watching is the first half. The second is writing it without the animation.