Lesson 01 · Data structures · 12 min
Walking a tree
Prefix, infix and postfix are one walk around the tree. Watch a pen trace it, then see where each order turns up in real software.

After this you can
- Write down the prefix, infix and postfix order of any binary tree without code
- Store a tree as linked nodes or as an array, and know when each is the right choice
- Recognise traversals in compilers, file systems, calculators and the browser
A tree is only useful if you can get at everything in it. Traversing a tree means visiting every node exactly once, in an order you chose on purpose. My notebook page has two of those orders, prefix and postfix, worked out by hand on an eleven-node tree. This lesson starts from that page and goes further: the third order, the trick that makes all three easy to do in your head, two ways to store a tree, and the places these walks run every day without anyone noticing.
Three rules, one tree
Every depth-first traversal does the same three jobs at each node: deal with the left subtree, deal with the right subtree, and visit the node itself, which usually means writing it down. The only question is when the visit happens.
| Order | Also called | Rule | On my tree |
|---|---|---|---|
| Prefix | Pre-order | visit, left, right | A B D E F H I G C M N |
| Infix | In-order | left, visit, right | D B H F I E G A M C N |
| Postfix | Post-order | left, right, visit | D H I F G E B M N C A |
On paper, applying those rules node by node gets confusing quickly. You lose your place three levels down. On my page you can see two crossed-out attempts before the right answers, so here's the trick I wish I'd known then.
The trick: walk around the outside
Put a pen just above and left of the root and trace one continuous loop around the whole tree, hugging every node and every branch, until you come back up the right side. You pass every node three times: once on its left, once underneath it, once on its right.
- Write a node down when you pass its left side, and you get prefix.
- Write it down when you pass underneath, and you get infix.
- Write it down when you pass its right side, and you get postfix.
Same loop every time. For prefix, write it down as the pen passes its left side.
It's the same walk every time, which is why the three orders are really one algorithm. A leaf like D gets all three moments in a row (left, under, right), so leaves keep their relative order in every traversal: D before H before I before G before M before N. Only the internal nodes move around. That's a quick way to check an answer.
Notice the tree is drawn so that each node's horizontal position is its infix position. Infix is literally reading the nodes left to right. For a binary search tree that means infix comes out sorted, which is the subject of the next lesson.
As code
The rules translate directly into recursion. These are Python generators, so they hand back one key at a time instead of building a list.
class Node: def __init__(self, key, left=None, right=None): self.key, self.left, self.right = key, left, right# The tree on my page.F = Node("F", Node("H"), Node("I"))E = Node("E", F, Node("G"))B = Node("B", Node("D"), E)C = Node("C", Node("M"), Node("N"))A = Node("A", B, C)def prefix(n): # visit, left, right if not n: return yield n.key yield from prefix(n.left) yield from prefix(n.right)def infix(n): # left, visit, right if not n: return yield from infix(n.left) yield n.key yield from infix(n.right)def postfix(n): # left, right, visit if not n: return yield from postfix(n.left) yield from postfix(n.right) yield n.keyprint(*prefix(A)) # A B D E F H I G C M Nprint(*infix(A)) # D B H F I E G A M C Nprint(*postfix(A)) # D H I F G E B M N C ARecursion uses the call stack to remember where you were. On a very deep tree that stack runs out: Python stops at about a thousand levels by default. The fix is to keep the stack yourself. For prefix, push the right child before the left so the left comes off first:
def prefix_iter(root): stack = [root] while stack: n = stack.pop() if not n: continue yield n.key stack.append(n.right) # pushed first, popped last stack.append(n.left)print(*prefix_iter(A)) # A B D E F H I G C M NThe fourth order: level by level
There's one more traversal that isn't a walk around the outside at all. Level order visits the root, then everything one level down, then the next level, left to right. Swap the stack for a queue (first in, first out) and you have it:
from collections import dequedef level_order(root): queue = deque([root]) while queue: n = queue.popleft() if not n: continue yield n.key queue.append(n.left) queue.append(n.right)print(*level_order(A)) # A B C D E M N F G H IStack gives you depth first, queue gives you breadth first. That one swap is the whole difference between DFS and BFS, which the search lesson uses to find paths through a map.
Storing a tree
The bottom of my page says there are two main ways to keep a tree in memory: linked lists and arrays. The drawing is the linked version. Each node is a box with three cells: a pointer to the left child, the data, and a pointer to the right child. The little upside-down Y I drew in the empty cells means “null”: no child there.
The array version, which is on my BST page, needs no pointers at all. Put the root at position 1. For a node at position i, the left child goes at 2i, the right child at 2i + 1, and the parent is at ⌊i / 2⌋.
- node
- E at 5
- left
- 2 × 5 = 10 → F
- right
- 2 × 5 + 1 = 11 → G
- parent
- ⌊5 / 2⌋ = 2 → B
The trade-off is clear in my own tree. It needs 21 slots for 11 nodes, because H and I sit four levels down on one side. A lopsided tree wastes most of its array. A complete tree, filled level by level with no gaps, wastes none, and that's exactly why the binary heap (the structure behind most priority queues) is stored this way.
| Linked nodes | Array | |
|---|---|---|
| Space | Two pointers per node, always | None for complete trees; huge gaps for lopsided ones |
| Find parent | Needs an extra pointer | ⌊i / 2⌋, free |
| Insert anywhere | Cheap: re-point two links | May need to grow the array |
| Cache-friendly | Nodes scattered in memory | One contiguous block |
| Used for | Search trees, syntax trees, the DOM | Heaps, segment trees, priority queues |
Where you'll meet these
Calculators and compilers
Write (3 + 4) × (5 − 2) as a tree with × at the root. Prefix gives × + 3 4 − 5 2 (Polish notation), postfix gives 3 4 + 5 2 − × (reverse Polish). Postfix needs no brackets and evaluates with a single stack, which is why old HP calculators used it and why compilers emit something very like it.
Your file system
Deleting a folder is postfix: you have to empty every subfolder before you can remove the folder itself. Copying one is prefix: create the folder first, then fill it. du adding up sizes is postfix too.
Every web page
The DOM is a tree, and the standard defines “tree order” as a prefix, depth-first walk. When querySelectorAll hands you elements in document order, that's the order you're getting.
Saving and loading
Writing a tree out as JSON or XML is a prefix walk: the parent opens, its children follow, the parent closes. Reading it back rebuilds the same tree.
You can watch Python do the postfix part. Ask it to disassemble an expression and the bytecode comes out in postfix order:
LOAD_NAME aLOAD_NAME bBINARY_OP (+)LOAD_NAME cLOAD_NAME dBINARY_OP (-)BINARY_OP (*)And evaluating postfix really is one stack and one loop:
def evaluate(tokens): stack = [] for t in tokens.split(): if t in "+-*/": b, a = stack.pop(), stack.pop() stack.append({"+": a + b, "-": a - b, "*": a * b, "/": a / b}[t]) else: stack.append(float(t)) return stack.pop()print(evaluate("3 4 + 5 2 - *")) # 21.0Try it
01Without looking above: what's the postfix order of my tree? Use the walk-around trick.
Show the answerHide the answer
02Evaluate the postfix expression 5 1 2 + 4 × + 3 −.
Show the answerHide the answer
03You need to free every node of a tree in a language without garbage collection. Which order, and why?
Show the answerHide the answer
04A tree's prefix is A B D C E and its infix is D B A E C. Draw it.
Show the answerHide the answer
Further reading
- Tree traversal (Wikipedia) ↗
Every variant, including the iterative and threaded versions, with pseudocode.
- Reverse Polish notation (Wikipedia) ↗
The history from Łukasiewicz to HP calculators, and the shunting-yard algorithm that turns infix into postfix.
- DOM Standard: tree order ↗
The one-line definition the whole web platform relies on.
- Python's dis module ↗
Disassemble your own code and watch expressions turn into stack operations.