Tree traversals: DFS orders and BFS
Visiting every node of a binary tree in the four classic orders, why recursion fits trees so well, and the "solve left, solve right, combine" template.
In short
A tree is a node with up to two subtrees, so most problems are recursion: solve the left, solve the right, combine. DFS (inorder, preorder, postorder) uses the call stack; BFS (level order) uses a queue. All visit each node once: O(n); space is O(h) for DFS and O(width) for BFS.
Four ways to walk a tree
Switch the order and watch what changes. The only difference between the three DFS orders is when the node is visited relative to its two recursive calls.
visit order
call stack
1def inorder(root):2 out = []3 def dfs(node):4 if not node: return5 dfs(node.left)6 out.append(node.val)7 dfs(node.right)8 dfs(root)9 return out
Variables
| Order | Visits | Typical use |
|---|---|---|
| Preorder | node, left, right | Copy or serialize a tree |
| Inorder | left, node, right | BST in sorted order, k-th smallest, validate a BST |
| Postorder | left, right, node | Delete a tree, height, anything needing the children's answers first |
| Level order (BFS) | level by level | Shortest path in an unweighted tree, right-side view, level averages |
The recursion template
def height(node):
if not node: return 0 # base case
left = height(node.left) # trust the recursion
right = height(node.right)
return 1 + max(left, right) # combine- Always start with the base case: the empty tree (
null). - Trust the recursive calls: assume they return the right answer for each subtree.
- Decide what each node returns and how to combine the two answers. Max depth, diameter, balanced check, path sum: same skeleton.
- Some problems need a value to flow down too (like a running sum or valid range): pass it as an argument.
Key takeaways
- 01Trees are recursive: base case, solve left, solve right, combine.
- 02Inorder on a BST gives sorted order.
- 03DFS uses the call stack (O(h)); BFS uses a queue (O(width)).
- 04Every traversal visits each node once: O(n).
Check your understanding
1 of 3
Which traversal returns a BST's values in sorted order?
Related topics
Recursion
A recursive function solves a problem by calling itself on a smaller version of it, until it reaches a base case it can answer directly. Each pending call waits on the call stack, so recursion costs memory too.
8 min read →Binary search trees
In a binary search tree every node is bigger than everything in its left subtree and smaller than everything in its right. Search, insert and delete follow one path: O(h), which is O(log n) if balanced and O(n) if it degenerates into a chain.
7 min read →BFS & DFS
A graph is nodes and edges. BFS uses a queue and explores in rings: the first time it reaches a node is via a shortest path (unweighted). DFS uses a stack (or recursion) and dives deep. Both cost O(V + E). Always keep a visited set, or cycles will loop forever.
10 min read →