Sub topic 5
Preorder, inorder, postorder, and level order
This chapter assumes you can read recursive Python, know what a queue and a stack are, and have the tree vocabulary from the earlier chapters (root, child, leaf, height). A traversal is a rule for visiting every node of a tree exactly once, in a fixed order. Traversals are the base for reconstruction, expression trees, and BST sorting, and GATE asks you to produce them by hand.
Two families of traversal
Trees have no single "next" element, so there are several valid orders. They fall into two families.
- Depth-first traversals go all the way down one branch before backing up. Preorder, inorder, and postorder belong here.
- Breadth-first traversal visits every node at one level before moving to the next. Level order is the only one in this family.
The three depth-first traversals differ in one thing: when the node itself is visited relative to its left and right subtrees.
| Traversal | Order of work at each node |
|---|---|
| Preorder | node, left subtree, right subtree |
| Inorder | left subtree, node, right subtree |
| Postorder | left subtree, right subtree, node |
The left subtree is always handled before the right one. A common memory aid is that the name says where the node goes: pre means before the subtrees, in means between them, post means after them.
A worked example
Use this tree for the rest of the chapter.
Trace each traversal by hand. For preorder, write the node before descending.
- Preorder: A, then the left subtree of A (B, D, E), then the right subtree (C, F). Result:
A B D E C F. - Inorder: the left subtree of A (D, B, E), then A, then the right subtree (C, F). Result:
D B E A C F. - Postorder: the left subtree (D, E, B), then the right subtree (F, C), then A. Result:
D E B F C A. - Level order: level 0 is A, level 1 is B and C, level 2 is D, E, F. Result:
A B C D E F.
Notice two facts that GATE questions exploit. The root is first in preorder and last in postorder. In inorder, the root splits the sequence: everything left of A came from A's left subtree.
Depth-first traversals in code
The complete program below defines the node class, the three recursive traversals, and a driver that builds the example tree.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def preorder(node, out):
if node:
out.append(node.key)
preorder(node.left, out)
preorder(node.right, out)
def inorder(node, out):
if node:
inorder(node.left, out)
out.append(node.key)
inorder(node.right, out)
def postorder(node, out):
if node:
postorder(node.left, out)
postorder(node.right, out)
out.append(node.key)
root = Node("A")
root.left = Node("B")
root.right = Node("C")
root.left.left = Node("D")
root.left.right = Node("E")
root.right.right = Node("F")
for walk in (preorder, inorder, postorder):
result = []
walk(root, result)
print(walk.__name__, result)Running it prints the three sequences traced above. Only the position of out.append(node.key) changes between the functions.
How the recursion behaves
Each traversal makes one call per node. It also makes one call per missing child, and those calls return immediately at the if node test. A tree with n nodes has n + 1 missing-child slots, so there are 2n + 1 calls in total. The time is Θ(n), and the visit order is fixed by the code, not by the key values.
The space cost is the call stack, which is as deep as the longest root-to-leaf path. That makes it O(h), where h is the height. For a balanced tree h is about log n. For a skewed tree h is n − 1, and Python raises RecursionError near depth 1000 by default. In an exam, remember that the extra space of recursive DFS is O(h), not O(1).
Level-order traversal with a queue
Recursion naturally follows the call stack, which is depth-first. To go level by level you need a first-in, first-out structure, so you use a queue.
from collections import deque
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def level_order(root):
out = []
queue = deque([root] if root else [])
while queue:
node = queue.popleft()
out.append(node.key)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return out
root = Node("A")
root.left = Node("B")
root.right = Node("C")
root.left.left = Node("D")
root.left.right = Node("E")
root.right.right = Node("F")
print(level_order(root))The queue holds nodes that were discovered but not yet visited. Because a node's children are added after the node's older siblings' children, the order stays level by level. Time is Θ(n). The queue size is bounded by the widest level, so extra space is O(w), where w is the maximum width. A perfect tree has about n/2 nodes in its last level, so level order can use Θ(n) space even when the tree is shallow.
Replacing the stack with your own
Recursive DFS is the same as DFS with an explicit stack. This iterative inorder version shows the mechanism and avoids the recursion limit.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def inorder_iterative(root):
out, stack, node = [], [], root
while node or stack:
while node:
stack.append(node)
node = node.left
node = stack.pop()
out.append(node.key)
node = node.right
return out
root = Node(2)
root.left = Node(1)
root.right = Node(3)
print(inorder_iterative(root))The inner loop pushes the whole left spine. Popping gives the next node in inorder, and then the loop moves to its right subtree. Space is still O(h).
Edge cases
- Empty tree. All four functions return an empty result. The guard
if nodeand the[root] if root else []expression handle this. Without the guard,level_order(None)would crash onNone.key. - Single node. All four traversals return just that key.
- Left-skewed chain (each node has only a left child). Preorder is root to leaf, and inorder and postorder are the reverse, leaf to root. Level order equals preorder.
- Right-skewed chain. Preorder and inorder are identical (root to leaf), postorder is the reverse, and level order equals preorder.
- Duplicate keys. Traversals visit nodes, not distinct keys, so duplicates appear each time. Duplicates become a problem only when you try to reconstruct a tree from the sequences, which a later chapter covers.
Common errors
- Visiting the right subtree before the left. Every standard traversal goes left first. Going right first gives the mirror-image order, which is a different sequence.
- Reading a subtree's nodes in the wrong place. Apply the rule recursively. In preorder, after A you must finish all of B's subtree (B, D, E) before touching C.
- Calling inorder output "sorted" for any tree. Inorder is sorted only for a binary search tree. For the example tree,
D B E A C Fis not sorted because the keys are not ordered by position. - Using a stack for level order. A stack gives a depth-first order. Level order needs a queue.
- Forgetting that a node with only one child still has a "missing" side. Inorder of C in the example puts C before F because C has no left subtree, not because the right child is special.
Summary of costs
| Traversal | Time | Extra space (recursive or stack/queue) |
|---|---|---|
| Preorder, inorder, postorder | Θ(n) | O(h) |
| Level order | Θ(n) | O(w), where w is the maximum width |
Exercise
A binary tree has preorder 1 2 4 5 3 and inorder 4 2 5 1 3. Give its postorder traversal.
Show answer
The first preorder key, 1, is the root. In the inorder sequence, 4 2 5 is left of 1 and 3 is right of it. The left subtree has preorder 2 4 5 and inorder 4 2 5, so its root is 2 with children 4 and 5. The right subtree is the single node 3. Postorder is left subtree, right subtree, root: 4 5 2 3 1.
Exercise
A skewed tree of 5 nodes has every node with only a right child, and the keys from root to leaf are 10, 20, 30, 40, 50. List its inorder, postorder, and level-order traversals.
Show answer
Inorder is 10 20 30 40 50, because each node has an empty left subtree and is visited before its right subtree. Postorder is 50 40 30 20 10, because each node is visited after its only child's subtree. Level order is 10 20 30 40 50, since each level holds one node.
Exercise
A recursive inorder function is run on a binary tree with 12 nodes. How many times is the function called in total, counting calls on empty children?
Show answer
Each of the 12 nodes is called once. A tree with n nodes has n + 1 empty child slots, so there are 13 calls on empty children. The total is 12 + 13 = 25, which matches 2n + 1.