Binary tree preorder traversal in C: solved exercise
Binary tree preorder traversal in C: solved exercise
If you searched for a solved preorder traversal of a binary tree in C, here are the two canonical implementations: the recursive version (natural and concise) and the iterative version with an explicit stack (required for very deep trees that would exhaust the system stack).
In preorder, the visit order is root → left child → right child (NLR: Node-Left-Right).
Problem statement
Given the tree:
Print the nodes in preorder using both the recursive and iterative approaches.
C solution
Expected output
Common mistakes
- In the iterative version, pushing the left child before the right: since the stack is LIFO, the right child must be pushed first so the left is processed first.
- Not checking
NULLbefore accessing children:n->left->datawithout verifyingn->left != NULLcauses a segmentation fault. - Not freeing tree memory: every node is allocated with
mallocand must be freed withfreeby traversing the tree in postorder. - Confusing preorder with inorder: preorder visits the root first (NLR); inorder visits the root between the children (LNR).
Practical use
Preorder traversal is used to serialize/copy a tree (insertion order reconstructs the same structure), to evaluate expressions in prefix notation (expression trees), and to print a filesystem directory hierarchy.
Recommended next exercise
- Binary tree postorder traversal in C: solved exercise
- Binary tree in C: solved exercise
- Queue in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
What is the difference between preorder, inorder, and postorder?
All three visit the same nodes but in different order:
- Preorder (NLR): root first, then left subtree, then right subtree.
- Inorder (LNR): left subtree, root, right subtree. Produces sorted values in a BST.
- Postorder (LRN): subtrees first, root last. Useful for freeing memory.
When should I use the iterative version instead of the recursive one?
The recursive version is more readable and sufficient for trees of reasonable depth. The iterative version is necessary when the tree can be very deep (thousands of levels) and the system stack is insufficient. In production, self-balancing trees like AVL or Red-Black have O(log n) depth, making recursion safe.
Is the preorder traversal unique for a given tree?
Yes: for a given binary tree, the preorder sequence is unique. However, knowing only the preorder is not enough to reconstruct the tree; the inorder is also needed (or NULL nodes must be explicitly marked in the serialization).