Algorithms Playbook
Data structureTime O(n) · Space O(h)9 min read

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.

Tree traversals
Order
Tree
Speed

visit order

0·
4213657

call stack

1def inorder(root):
2 out = []
3 def dfs(node):
4 if not node: return
5 dfs(node.left)
6 out.append(node.val)
7 dfs(node.right)
8 dfs(root)
9 return out
Depth-first, inorder: left, then the node, then right (a BST comes out sorted).

Variables

orderinorder
Step 1/38· Visits: 0
DFS uses a stack (the recursion), BFS uses a queue. Both touch every node once: O(n).
OrderVisitsTypical use
Preordernode, left, rightCopy or serialize a tree
Inorderleft, node, rightBST in sorted order, k-th smallest, validate a BST
Postorderleft, right, nodeDelete a tree, height, anything needing the children's answers first
Level order (BFS)level by levelShortest 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