Binary tree postorder traversal in C: solved exercise
Binary tree postorder traversal in C: solved exercise
If you searched for a solved postorder traversal of a binary tree in C, here are the recursive and two-stack iterative versions. Postorder visits nodes in the order left child → right child → root (LRN), making it the natural traversal for freeing a tree’s memory.
The iterative postorder is more complex than iterative preorder because the root is processed last; the two-stack trick reverses the right-first preorder to obtain postorder.
Problem statement
Given the tree:
Print the nodes in postorder using both the recursive and iterative approaches.
C solution
Expected output
Common mistakes
- Trying to use a single stack without a tracking pointer: possible but requires an extra variable to track the last visited node, making the implementation harder. Two stacks are clearer.
- Getting the LRN order wrong: swapping the children gives RLN — a mirrored traversal.
- Freeing memory in preorder instead of postorder: freeing a node before its children leaves dangling pointers and prevents reaching the children.
- Using
intas the stack element type instead ofNode *: the stack must store node pointers.
Practical use
Postorder is used to free tree memory (children must be freed before the parent), to evaluate postfix (RPN) expressions, to compute subdirectory sizes in a file system tree, and in compiler code generation (operands are evaluated before the operator).
Recommended next exercise
- Binary tree preorder traversal in C: solved exercise
- Binary tree in C: solved exercise
- Min-heap in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Why does the iterative postorder need two stacks?
Because postorder processes the root last, which is contrary to a LIFO stack’s natural behavior. The trick is to perform a preorder-like traversal visiting the right child first (root-right-left), store nodes in a second stack, and then draining it gives the reverse order: left-right-root = postorder.
How can you tell if a traversal is in postorder without running the code?
For the exercise tree: leaf nodes (4, 5, 6) always appear before their parents (2, 3), and the root (1) always appears last. If the last element is the root and children always precede their parents, the traversal is postorder.
Can postorder be implemented with a single stack?
Yes, by maintaining a last_visited pointer tracking the most recently processed node. When the right child has already been visited (or does not exist), the root is processed. The logic is more complex; two stacks are preferable for clarity.