Preorder, inorder, postorder, level order: when do you use each?
Question
A shop keeps product prices in this binary search tree (BST):
30
/ \
20 40
/ \ \
10 25 50- Write the keys in preorder, inorder, postorder and level order.
Match each order with the job it fits best:
- (a) list the prices from lowest to highest;
- (b) find the size of every subtree;
- (c) save the tree so you can rebuild exactly the same shape;
- (d) show the tree one depth at a time.
Show hints (3)
- "WHEN YOU WRITE IT"
Preorder, inorder and postorder all walk the tree the same way. The only difference is when you write down a node's key: before its children, between them or after both.
- "WHAT THE BST GIVES"
In a BST, everything left of a node is smaller and everything right is larger. Which order visits left, then the node, then right?
- "CHILDREN FIRST"
A subtree's size is 1 plus the sizes of its two children. Which order reaches a node only after both children are done? For level order, keep a queue.
Show checked explanation
Preorder is 30 20 10 25 40 50 and fits (c), saving the shape. Inorder is 10 20 25 30 40 50, the sorted prices (a). Postorder is 10 25 20 50 40 30: children before parents, so (b), subtree sizes. Level order, built with a queue, is 30 20 40 10 25 50 and fits (d).
# A node is (key, left, right). None means no child. tree = (30, (20, (10, None, None), (25, None, None)), (40, None, (50, None, None))) def dfs(node, pre, ino, post): if node is None: return key, left, right = node pre.append(key) # before the children dfs(left, pre, ino, post) ino.append(key) # between them dfs(right, pre, ino, post) post.append(key) # after both pre, ino, post = [], [], [] dfs(tree, pre, ino, post) print(pre, ino, post, sep="\n")
[30, 20, 10, 25, 40, 50] [10, 20, 25, 30, 40, 50] [10, 25, 20, 50, 40, 30]
Code run on CPython 3.12 against the tree above. Checked by an editor other than the author.
Walkthrough
The three depth-first orders take the same path through the tree. They differ only in when they record the key. Level order is different: it visits the tree one depth at a time.
| order | rule | result | job |
|---|---|---|---|
| preorder | node, left, right | 30 20 10 25 40 50 | (c) save the shape |
| inorder | left, node, right | 10 20 25 30 40 50 | (a) sorted prices |
| postorder | left, right, node | 10 25 20 50 40 30 | (b) subtree sizes |
| level order | depth by depth | 30 20 40 10 25 50 | (d) one depth at a time |
Why each one fits:
- Inorder sorts a BST. Everything left of a node is smaller and everything right is larger. So left, node, right gives the keys in order.
- Postorder sees children first. A subtree's size is 1 plus its children's sizes, and those are ready when you reach the parent. 20 gets 1 + 1 + 1 = 3. The root gets 1 + 3 + 2 = 6.
- Preorder writes each parent before its children. Insert 30, 20, 10, 25, 40, 50 into an empty BST, and every key lands where it was. Level order also puts parents first, so it would work too. Inorder can't: inserting sorted keys builds a chain.
- Level order needs a queue. Take a node from the front, then add its children to the back:
from collections import deque def level_order(root): order, queue = [], deque([root] if root else []) while queue: key, left, right = queue.popleft() order.append(key) queue.extend(child for child in (left, right) if child) return order
level_order(tree) returns [30, 20, 40, 10, 25, 50]. Each of the four orders visits every node once, so each is O(n).
Common mistakes
- Using
list.pop(0)for the queue. Each call moves every remaining item one place, so level order on n nodes becomes O(n²).deque.popleft()is O(1). - Expecting inorder to be sorted in any binary tree. That only holds in a BST, where the keys are placed by size.
- Thinking preorder alone describes any binary tree.
[1, 2]fits 2 as the left child and 2 as the right child. In a BST it works, because the keys decide the side. - Using a stack, with
pop(), where the queue belongs. The same loop then visits 30, 40, 50, 20, 25, 10. That is depth-first, not level by level.
Follow-up questions
- "Write inorder without recursion." Use a stack. Go left as far as you can, pushing each node. Pop a node, record its key, then move to its right child and repeat. The stack never holds more nodes than the tree is tall. On a very deep tree this also avoids
RecursionError. - "Print the tree with one line per level." Process the queue in rounds. At the start of a round,
len(queue)is the number of nodes on that level. Pop exactly that many and print their keys together. For this tree you get[30], then[20, 40], then[10, 25, 50].
What a strong answer covers
Gives all four orders correctly. Links each one to a job: inorder for sorted output, postorder when a parent needs its children's results, preorder to save a shape, a queue for level order. Uses deque and can write inorder with a stack.
Open in interactive practice deck →