Tree Traversals — Inorder, Preorder, Postorder, Level Order — Complete Beginner Guide
Learning Objectives
- Differentiate the three depth-first orders
- Implement recursive inorder, preorder, and postorder
- Implement level order with a queue
- Match traversal choice to real tasks
- State the time and space cost of traversal
Why Traversal Matters
Trees do not have a single natural index like arrays. To visit every node you need a traversal plan. The plan decides the order values appear.
Three depth-first orders vary by when you visit the root relative to the children. Level order visits by depth using a queue.
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def build_sample():
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
return root
root = build_sample()
Inorder: Left, Root, Right
Visit the left subtree, then the root, then the right subtree. On a binary search tree, inorder produces sorted ascending keys.
def inorder(node, out):
if node is None:
return
inorder(node.left, out)
out.append(node.value)
inorder(node.right, out)
result = []
inorder(root, result)
print(result) # 4, 2, 5, 1, 6, 3, 7
Use inorder to stream sorted data from a BST.
Preorder: Root, Left, Right
Visit the root first. Preorder produces a natural prefix snapshot of the tree, useful for copying or serializing structure.
def preorder(node, out):
if node is None:
return
out.append(node.value)
preorder(node.left, out)
preorder(node.right, out)
result = []
preorder(root, result)
print(result) # 1, 2, 4, 5, 3, 6, 7
Postorder: Left, Right, Root
Visit children before the root. Postorder fits cleanup tasks such as freeing memory or deleting folders that must empty first.
def postorder(node, out):
if node is None:
return
postorder(node.left, out)
postorder(node.right, out)
out.append(node.value)
result = []
postorder(root, result)
print(result) # 4, 5, 2, 6, 7, 3, 1
Level Order: Breadth by Depth
Level order visits nodes top to bottom and left to right. A queue drives the walk.
from collections import deque
def level_order(root):
if root is None:
return []
out = []
queue = deque([root])
while queue:
node = queue.popleft()
out.append(node.value)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return out
print(level_order(root)) # 1, 2, 3, 4, 5, 6, 7
Comparison Table
| Order | Pattern | Top Tool | Common Use |
|---|---|---|---|
| Inorder | Left, Root, Right | Recursion | Sorted BST output |
| Preorder | Root, Left, Right | Recursion | Copy or serialize |
| Postorder | Left, Right, Root | Recursion | Delete or free |
| Level order | By depth | Queue | Shortest levels, printing |
Complexity
| Metric | Value |
|---|---|
| Time | O(n) for all four orders |
| Space recursion depth | O(h) where h is height |
| Space level order queue | Up to O(n) |
| Balanced height h | About log n |
| Skewed height h | About n |
Every traversal touches each node once, so time stays linear. Space follows the frontier of the search.
Iterative Inorder with a Stack
Recursion is clear, but an explicit stack can avoid deep call frames.
def inorder_iterative(root):
out = []
stack = []
current = root
while current is not None or stack:
while current is not None:
stack.append(current)
current = current.left
current = stack.pop()
out.append(current.value)
current = current.right
return out
print(inorder_iterative(root))
Traversal Selection Drill
Quiz yourself with short scenarios until the choice becomes automatic. Output sorted keys from a BST means inorder. Serialize a tree for storage often starts with preorder because the root anchors reconstruction. Delete files and folders uses postorder so children clear before parents. Print an org chart level by level uses level order with a queue.
You can also reconstruct a tree when you hold two appropriate traversals. Inorder plus preorder is enough for binary trees with unique keys. Inorder plus postorder works too. Level order alone is not enough without extra child markers.
| Goal | First Choice |
|---|---|
| Sorted stream | Inorder |
| Copy structure | Preorder |
| Cleanup or free | Postorder |
| Wave printing | Level order |
| Closest to root first | Preorder or level order |
Write the four orders on an index card and drill them daily for a week. Traversal recall pays off in almost every tree problem you will meet.
Traversal Complexity Refresher
Every traversal touches each node once, so time is always O(n) regardless of order. The difference is in auxiliary space and in the order results appear.
Recursive depth-first traversals keep one stack frame per active path, so space follows height h. A balanced tree holds about log n frames. A degenerate tree can hold n frames and risk hitting recursion limits on large inputs.
Level order keeps a queue of the frontier. On a bushy tree the last level alone can hold about n over two nodes, so peak queue memory approaches O(n).
| Order | Tool | Space Driver |
|---|---|---|
| Inorder recursive | Call stack | Height |
| Preorder recursive | Call stack | Height |
| Postorder recursive | Call stack | Height |
| Level order | Queue | Width of frontier |
Convert one recursive traversal to an explicit stack whenever the input might be extremely deep. Non-recursive versions also make space costs easier to explain in system design discussions.
Key Takeaways
💡
- Inorder, preorder, and postorder differ only in root timing
- Inorder on a BST yields sorted keys
- Level order uses a queue to visit by depth
- All traversals run in O(n) time
- Space follows tree height for recursion and width for queues
Practice Questions
- Given inorder 4, 2, 5, 1, 6, 3, 7 and preorder 1, 2, 4, 5, 3, 6, 7, reconstruct the tree.
- Which traversal should free a binary tree safely, and why?
- Rewrite level order so it returns values grouped as separate lists per level.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions