Skip to content
← Notes

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.

My handwritten notes: Prefix and postfix traversal, and storing a tree in memory

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.

OrderAlso calledRuleOn my tree
PrefixPre-ordervisit, left, rightA B D E F H I G C M N
InfixIn-orderleft, visit, rightD B H F I E G A M C N
PostfixPost-orderleft, right, visitD 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.
DBHFIEGAMCN
prefix

Same loop every time. For prefix, write it down as the pen passes its left side.

Drag the slider to move the pen, or press play. The dots mark where each node gets written for the order you picked.

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.

traversal.pypython
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 A

Recursion 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:

prefix without recursionpython
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 N

The 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:

level orderpython
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 I

Stack 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⌋.

D4B2H20F10I21E5G11A1M6C3N7
node
E at 5
left
2 × 5 = 10 → F
right
2 × 5 + 1 = 11 → G
parent
⌊5 / 2⌋ = 2 → B
Every node's family is arithmetic: no pointers stored at all. The cost is the empty slots, here 10 of 21.

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 nodesArray
SpaceTwo pointers per node, alwaysNone for complete trees; huge gaps for lopsided ones
Find parentNeeds an extra pointer⌊i / 2⌋, free
Insert anywhereCheap: re-point two linksMay need to grow the array
Cache-friendlyNodes scattered in memoryOne contiguous block
Used forSearch trees, syntax trees, the DOMHeaps, 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:

python -c "import dis; dis.dis('(a + b) * (c - d)')" (trimmed)output
LOAD_NAME   aLOAD_NAME   bBINARY_OP   (+)LOAD_NAME   cLOAD_NAME   dBINARY_OP   (-)BINARY_OP   (*)

And evaluating postfix really is one stack and one loop:

evaluate postfixpython
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.0

Try it

01Without looking above: what's the postfix order of my tree? Use the walk-around trick.

Show the answer
D H I F G E B M N C A. Write each node as the pen passes its right side.

02Evaluate the postfix expression 5 1 2 + 4 × + 3 −.

Show the answer
14. Push 5, 1, 2; + gives 3; push 4; × gives 12; + gives 17; push 3; − gives 14.

03You need to free every node of a tree in a language without garbage collection. Which order, and why?

Show the answer
Postfix. A node can only be freed after both children are, or you lose the pointers to them.

04A tree's prefix is A B D C E and its infix is D B A E C. Draw it.

Show the answer
A is the root (first in prefix). In infix, D B are left of A and E C are right. On the left, B comes first in prefix, so B is that subtree's root with D as its left child. On the right, C comes first, so C is the root with E as its left child.

Further reading

07 · Contact

Write to me.

I'm open to software engineering and data roles, and to freelance work. If you have a process that still runs on copy and paste, I'd like to hear about it.