Skip to content

Pre-order, in-order and post-order, drawn

BasicsUnder the hoodYou should know: recursion

Pre-order, in-order and post-order sound like three algorithms. They are one recursive walk, and the only difference is the line where you write the node down.

01 One walk, three moments

A recursive walk over a binary tree reaches every node three times: when the call starts, after the left subtree returns, and after the right subtree returns. The calls happen in the same order every time. What changes is which of those three moments you use to visit the node: print it, add it to a list, or work something out from it.

Python
def walk(node):
if node is None:
return
# 1. on the way in: nothing below has been seen yet
walk(node.left)
# 2. in between: the left subtree is done, the right is not
walk(node.right)
# 3. on the way out: both subtrees are done

Put the visit at moment 1 and you get pre-order. At moment 2, in-order. At moment 3, post-order. The rest of the function does not change.

02 Three places to put the visit

Here are the three walks side by side. Read them line by line: only the position of out.append moves.

walks.py
def preorder(node, out):
if node is None:
return
out.append(node.val) # visit first
preorder(node.left, out)
preorder(node.right, out)
def inorder(node, out):
if node is None:
return
inorder(node.left, out)
out.append(node.val) # visit in between
inorder(node.right, out)
def postorder(node, out):
if node is None:
The visit's position decides the order
OrderVisit happensPattern
Pre-orderbefore both subtreesnode, left, right
In-orderbetween the subtreesleft, node, right
Post-orderafter both subtreesleft, right, node

03 In-order, call by call

Take a five-node tree: A at the root, B and C below it, and D and E under B. Watch the call stack: a node is written only once its left call has come back.

In-order walk
Step 1 of 14
Tree
A
B
D
E
C
Call stack
Empty
Output
Empty
  • not called yet
  • call paused
  • call running
  • just pushed or written
  • written

The walk is about to start at the root A. No call has run, so the stack and the output are empty.

0 written

The stack never held more than three calls: one per level of the tree. The memory a recursive walk needs grows with the tree's height, not with how many nodes it has.

04 Every order on one tree

Run the same walk with the visit in each place, and every node gets three positions. The calls are identical; only the moment of writing differs.

Position of each node in pre-order · in-order · post-order
Tags: pre · in · post
A1 · 4 · 5
B2 · 2 · 3
D3 · 1 · 1
E4 · 3 · 2
C5 · 5 · 4

A is 1st in pre-order, 4th in in-order and 5th (last) in post-order. A leaf such as D comes out early in all three, because nothing below it has to wait.

main.py
class Node:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
root = Node("A", Node("B", Node("D"), Node("E")), Node("C"))
for walk in (preorder, inorder, postorder):
out = []
walk(root, out)
print(walk.__name__, " ".join(out))
Text
preorder A B D E C
inorder D B E A C
postorder D E B C A

05 What each order is for

Pick the order by what the visit needs to know.

Pre-orderParent firstThe node is handled before anything below it. Use it to copy or save a tree, since you can rebuild a parent before its children arrive.
In-orderLeft to rightNodes come out in their left-to-right position. In a binary search tree that is sorted order.
Post-orderChildren firstThe node is handled after both subtrees. Use it when a node's answer depends on its children: height, size, or freeing memory.

Maximum depth is a post-order walk. A node cannot know its depth until both children have reported theirs, so the work happens on the way out.

Python
def max_depth(node):
if node is None:
return 0
left = max_depth(node.left)
right = max_depth(node.right)
return 1 + max(left, right) # the visit: after both children

06 The same walk with your own stack

Recursion keeps the paused calls on the call stack for you. You can keep them yourself in a list. The loop below does exactly what the trace showed: dive left pushing nodes, pop one, write it, then turn right.

Python
def inorder_iter(root):
out, stack, node = [], [], root
while stack or node:
while node: # dive left, remembering each node
stack.append(node)
node = node.left
node = stack.pop() # the deepest unwritten node
out.append(node.val) # visit in between
node = node.right # then walk its right side
return out

This version has no depth limit beyond memory, which matters on very deep trees. Pre-order is the easiest to write this way; post-order is the hardest, because a node has to wait for two subtrees, not one.

07 When it goes wrong

pre[::-1]Reversed pre-order is not post-orderOn our tree, reversed pre-order is C E D B A but post-order is D E B C A. What reverses into post-order is node, right, left: A C B E D reversed.
RecursionErrorA deep tree hits the recursion limitCPython stops at a depth of about 1,000 calls by default (sys.getrecursionlimit()). A tree shaped like a long chain gets there. Use the explicit stack instead.
node.left.valReading a child without checkingLeaves have None children. Check node is None at the top of the function, once, instead of before every child access.
inorder(root)Expecting sorted output from any treeIn-order gives left-to-right position. It is sorted only when the tree is a binary search tree.
Looking for level order hereRow by row is none of the three. It needs a queue, not a stack: that is breadth-first search.

08 Check yourself

Question

A tree has root 5. Its left child is 3, and 3 has a right child 4. What does in-order write?

Question

In the trace, which calls are on the stack at the moment E is written?

Question

You need to free every node, and a node must be freed only after its children. Which order?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?