Tree Traversals: In-Order, Pre-Order and Post-Order as a Tour of the House
A traversal is a tour that visits every node once. Left side, this room, right side gives Emma's seven cards sorted, 20 to 80. Pre-order and post-order just move the moment you print, and one missing None check crashes the tour.
What you will learn
- Explain a traversal as visiting every node of a tree exactly once
- Walk in-order, pre-order and post-order by hand and predict their output
- See why in-order on a binary search tree gives sorted values
- Explain the O(n) cost, the room a tall tree needs, and why the None check is the stopping rule
Before you start
- Binary Search Trees
- Recursion
Here is Emma's tree from Binary search trees: seven cards, smaller on the left, bigger on the right. Now she wants a list of every card, smallest to biggest. Finding one card follows just one path down. This time you need every card, each exactly once. Where do you start, and how do you know you're done?
Visiting every node of a tree exactly once is called a traversal. You can think of it as a tour of the tree.
A tour of every room
Imagine Emma's house. It has seven rooms, and every room has at most two doors leading further in, one on the left and one on the right. Just like the cards.
The tour rule: in every room, first visit everything on the left, then this room, then everything on the right. You start at the Hall, but the Hall has to wait, because its left side comes first. So you go to the Living room, which also waits, and then to the Kitchen. The Kitchen has no door on its left, so you visit it: number one. Then the Living room, the Study, and only then the Hall, at number four. Then the right side.
There are other tours too. You can say hello as you walk in (this room first), or switch the lights off on the way out (this room last).
Play the in-order tour
- Start at 50. It has to wait, because its whole left side comes first. Go left to 30, which waits too. Go left to 20.
- 20 has nothing on its left, so print 20. Nothing on its right either, so step back to 30.
- 30's left side is done: print 30. Its right side is 40, with no children: print 40.
- Back up to 50. The whole left side is done: print 50.
- Right side of 50: go to 70, which sends you left to 60. Print 60, then 70, then 80.
Every card once, and sorted, and you never sorted anything. In a search tree, smaller is always on the left, so left side, this card, right side meets the cards in order.
Three tours, one rule
Run the same rule again and only move the moment you print:
- In-order (left, node, right). 20 comes first, the root is number four. Smallest to biggest.
- Pre-order (node, left, right). The root comes first, so parents always come before their children. That's handy when you want to copy a tree, or show a folder before what's inside it.
- Post-order (left, right, node). The root comes last, so children come before their parents. That's what you want to clean up a tree, like deleting the files in a folder before the folder.
A calculator tree uses post-order too: it works out the two numbers first, and then the plus or the times.
The code
The Node and NumberTree are the same as last time, with one small addition, get_root, so a tour can start at the top:
from node import Node
class NumberTree:
def __init__(self):
self.root = None
def get_root(self):
return self.root
def insert(self, value):
self.root = self._insert(self.root, value)
def _insert(self, node, value):
if node is None:
return Node(value)
if value < node.value:
node.left = self._insert(node.left, value)
else:
node.right = self._insert(node.right, value)
return node
And the three tours:
def in_order(node):
if node is None:
return # no node: go back
in_order(node.left) # the left side first
print(node.value, end=" ") # then this node
in_order(node.right) # then the right side
def pre_order(node):
if node is None:
return
print(node.value, end=" ") # this node FIRST
pre_order(node.left)
pre_order(node.right)
def post_order(node):
if node is None:
return
post_order(node.left)
post_order(node.right)
print(node.value, end=" ") # this node LAST
The first two lines of each are the most important: if there's no node, go back. The three functions are the same apart from where the print sits: in the middle, first, or last.
from number_tree import NumberTree
from walks import in_order, pre_order, post_order
tree = NumberTree()
for card in (50, 30, 70, 20, 40, 60, 80):
tree.insert(card)
print("In-order: ", end="")
in_order(tree.get_root())
print()
print("Pre-order: ", end="")
pre_order(tree.get_root())
print()
print("Post-order: ", end="")
post_order(tree.get_root())
print()
In-order: 20 30 40 50 60 70 80
Pre-order: 50 30 20 40 70 60 80
Post-order: 20 40 30 60 80 70 50
Same tree, three tours, three orders.
Break it: no stopping rule
from number_tree import NumberTree
def in_order(node):
in_order(node.left) # no None check!
print(node.value, end=" ")
in_order(node.right)
tree = NumberTree()
tree.insert(50)
in_order(tree.get_root())
Traceback (most recent call last):
...
File "no_stop_app.py", line 5, in in_order
in_order(node.left) # no None check!
^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'left'
A tree with one card, 50. Its left child is None, so the second call gets None, and node.left on None fails. Without the None check, the tour walks through a door that isn't there. That one line is the way back.
The cost
A tour can't skip anything. Seven cards means seven visits; a million cards means a million visits. Compare finding one card: about three steps in the small tree, about twenty in a balanced tree of a million. So a tour grows in step with the number of cards: ten times the cards, ten times the visits.
There's a second cost: room. While you go down, the rooms you've passed wait behind you. Add five cards biggest first (50, 40, 30, 20, 10) and every card has a door on the left only. Reaching 10, four rooms are waiting at once. The tour still prints every card once, sorted, but the rooms waiting are as many as the tree is tall: about twenty for a balanced million, and a million for a lopsided one, where the tour can run out of room.
| Question | Answer |
|---|---|
| Time for any tour | O(n), every node once |
| Room while touring | as many waiting rooms as the tree is tall |
| Find one card (balanced) | O(log n), one path |
| Without the None check | crash |
Try it yourself
Add a function count that returns 1 plus the count of the left side plus the count of the right side (and 0 for None), and print how many cards the tree holds. You should get 7.
Related courses on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Data Structures and Algorithms Concepts: No Coding Needed
How stacks, trees, hash tables, sorting and graphs really work, step by step, with pictures.View on Udemy ↗: Data Structures and Algorithms Concepts: No Coding Needed (paid course, opens in a new tab)Related posts
What a Data Structure Is, and How Memory Works
Memory is a long row of numbered boxes, and opening any box is equally quick. A data structure is an agreed way of arranging things in those boxes, plus a few small notes. See with six songs on a phone why every structure is quick at some things and slow at others.
Arrays and Dynamic Arrays: Full? Get a Box Twice the Size
A fixed array never gets longer. A dynamic array fills its box, then copies everything into a box twice the size. Build one for Emma's playlist in Python, count the copies and shifts, and see why adding at the end stays cheap while inserting at the front costs almost 50 million shifts for 10,000 songs.
Linked Lists: A Chain of Clues, Built in Python
In a linked list every node holds a value and the address of the next node. Build a treasure hunt chain in Python: a new first clue is two moves at any size, slipping a clue in or out is just changing next, but reaching clue number i is a walk of i hops.
Stacks: Last In, First Out, With the Undo Button
A stack is last in, first out: the newest thing you put on is the first thing you take off. Build Emma's undo button in Python from a list and one top index, push, pop and peek in one step each, undo after a million edits, and see what happens when you pop an empty stack.
