Binary Tree Traversal in Data Structure
Traversal refers to visiting every node of a binary tree exactly once in a specific order. There are four common traversal techniques: Inorder, Preorder, Postorder, and Level Order.
Inorder Traversal (Left, Root, Right)
Visits the left subtree, then the root, then the right subtree. For a Binary Search Tree, inorder traversal produces values in sorted order.
def inorder(node, result=None):
if result is None:
result = []
if node:
inorder(node.left, result)
result.append(node.val)
inorder(node.right, result)
return result
Preorder Traversal (Root, Left, Right)
Visits the root first, then the left subtree, then the right subtree. Useful for creating a copy of the tree.
def preorder(node, result=None):
if result is None:
result = []
if node:
result.append(node.val)
preorder(node.left, result)
preorder(node.right, result)
return result
Postorder Traversal (Left, Right, Root)
Visits the left subtree, then the right subtree, then the root. Useful for deleting a tree or evaluating expression trees.
def postorder(node, result=None):
if result is None:
result = []
if node:
postorder(node.left, result)
postorder(node.right, result)
result.append(node.val)
return result
Level Order Traversal (Breadth First)
Visits nodes level by level, using a queue.
from collections import deque
def level_order(root):
if not root:
return []
result, queue = [], deque([root])
while queue:
node = queue.popleft()
result.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
return result
Complexity
| Traversal | Time | Space |
|---|---|---|
| All four traversals | O(n) | O(h) for recursive, O(n) for level order |
Dry Run on a Small Tree
Traversal orders are easiest to remember when you trace them on paper. Take this tree, where 1 is the root:
1
/ \
2 3
/ \ \
4 5 6
| Traversal | Visit order | Output |
|---|---|---|
| Preorder | Root, Left, Right | 1 2 4 5 3 6 |
| Inorder | Left, Root, Right | 4 2 5 1 3 6 |
| Postorder | Left, Right, Root | 4 5 2 6 3 1 |
| Level order | Level by level, left to right | 1 2 3 4 5 6 |
A handy trick: draw a line around the tree starting at the left of the root. Preorder prints a node when you pass its left side, inorder when you pass underneath it, and postorder when you pass its right side.
Iterative Inorder with an Explicit Stack
Recursive code is short, but a very deep or skewed tree can exceed Python's recursion limit. The iterative version simulates the call stack yourself. It keeps going left while pushing nodes, then pops a node, records it, and moves to its right child.
def inorder_iterative(root):
result, stack = [], []
current = root
while current or stack:
while current: # go as far left as possible
stack.append(current)
current = current.left
current = stack.pop() # leftmost unvisited node
result.append(current.val)
current = current.right # then explore its right subtree
return result
Preorder can be done iteratively in a similar way: push the root, then in a loop pop a node, record it, push its right child and then its left child, so the left side is processed first.
Choosing the Right Traversal for a Problem
- Validate a BST or find the k-th smallest value: inorder, because it visits keys in sorted order.
- Serialize or clone a tree: preorder, since the root is written before its children and can be rebuilt in the same order.
- Compute height, size or free memory: postorder, because a node needs results from both children first.
- Find the minimum depth, print by level or connect siblings: level order with a queue.
Interviewers also like the reconstruction question: given preorder and inorder lists, rebuild the tree. Preorder tells you the root, and its position in the inorder list splits the remaining values into left and right subtrees. Preorder alone, or postorder alone, is not enough when values can appear in more than one tree shape.
Common Mistakes When Writing Traversals
- Using a mutable default argument such as
result=[], which keeps values between calls. The existing code avoids this withNone. - Forgetting the empty-tree check, which causes an attribute error on
None. - Using a Python list with
pop(0)for level order; it is slow for large trees, so preferdeque. - Mixing up the order of pushing children in iterative preorder.
Takeaway: practise each traversal on one sample tree by hand, then code both the recursive and iterative versions until you can write them without notes.