Traversals
Preorder visits a node, then its left subtree, then its right. Inorder visits left, node, right. Postorder visits left, right, node. Recursion writes each in three lines; with an explicit stack, each can also be done iteratively, which avoids deep call stacks and is a common interview follow-up.
How to recognise it
- The answer is a list of all node values in some order.
- You must process children before the parent (postorder) or the parent before children (preorder).
- A BST's sorted order is wanted (inorder).
The three depth-first orders
What a node, a child, a leaf and a level are is on the Structures page.
| Order | Rule | For the tree above |
|---|---|---|
| preorder | node, left, right | 1 2 4 5 3 6 7 |
| inorder | left, node, right | 4 2 5 1 6 3 7 |
| postorder | left, right, node | 4 5 2 6 7 3 1 |
visit(n):
if n is null: return
(preorder: record n here)
visit(n.left)
(inorder: record n here)
visit(n.right)
(postorder: record n here)
Without recursion
- Preorder: a stack; pop a node, record it, push its right then its left.
- Inorder: walk left pushing nodes; pop one, record it, move to its right child; repeat.
- Postorder: do "node, right, left" with the preorder method and reverse the result.
All of them are O(n) time and O(h) extra space, where h is the height.
Common mistakes
- Pushing the left child first in the iterative preorder.
- Forgetting that a skewed tree makes
h = n, so deep recursion can overflow.
Problems
- Binary Tree Inorder Traversaleasyguide ready
- Binary Tree Preorder Traversaleasyguide ready
- Binary Tree Postorder Traversaleasyguide ready
- Pre, Post, Inorder in one traversalmediumguide ready