Tree Traversals (DFS & BFS) Resource - aloalgo

Tree Traversals (DFS & BFS)

Tree traversal is the process of visiting every node in a tree exactly once. There are two main approaches: Depth-First Search (DFS) which goes deep before wide, and Breadth-First Search (BFS) which goes wide before deep.

DFS Traversal Orders

DFS has three variations based on when you process the current node relative to its children:
OrderPatternUse Case
PreorderNode → Left → RightCopy tree, prefix expressions
InorderLeft → Node → RightBST gives sorted order
PostorderLeft → Right → NodeDelete tree, postfix expressions

Preorder Traversal

Process the node first, then recurse on left and right children.

Inorder Traversal

Recurse on left, process the node, then recurse on right. For BSTs, this gives nodes in sorted order.

Postorder Traversal

Recurse on both children first, then process the node. Useful when you need information from children before processing the parent.

BFS / Level Order Traversal

Visit all nodes at depth d before visiting nodes at depth d+1. Uses a queue to process nodes level by level.

DFS vs BFS

AspectDFSBFS
Data structureStack (or recursion)Queue
Space complexityO(h) height of treeO(w) width of tree
Best forDeep trees, path problemsWide trees, shortest path
Finds shortest path?NoYes (unweighted)

When to Use DFS vs BFS

Use DFS when:
  • You need to explore all paths (path sum, root-to-leaf)
  • You need information from children before processing parent
  • The answer is likely deep in the tree
  • You're doing tree transformations or modifications
Use BFS when:
  • You need level-by-level processing
  • You're finding minimum depth or shortest path
  • You need to process nodes closest to root first
  • The answer is likely near the top of the tree

Common Interview Tips

  1. Know all three DFS orders: Be able to write preorder, inorder, and postorder from memory.
  2. Inorder for BST: If the tree is a BST, inorder gives you sorted values.
  3. BFS for level-based problems: Minimum depth, level averages, right-side view.
  4. Iterative vs recursive: Know both - iterative avoids stack overflow for deep trees.
Was this helpful?
© 2026 aloalgo. All rights reserved.