Home
DSA Visualizer
Data Structures
Tree Traversal
Tree Traversal
Tree traversal is the set of algorithms for visiting every node in a tree data structure.
VISIT
Output so far
Left subtree, then root, then right. On a binary SEARCH tree this comes out sorted.
Visit 10 — position 1 of 7.
Next
Visit 25 — position 2 of 7.
Order
Intuition
Imagine exploring a maze. You can either explore all nearby paths first (BFS) or go as deep as possible down one path before backtracking (DFS).
Concept
Tree traversal is the process of visiting each node in a tree data structure exactly once. BFS uses a Queue to visit nodes level by level. DFS uses a Stack (or recursion) to go deep into branches.
How it Works
- BFS (Level Order): Visits nodes level by level (Root, then Level 1, then Level 2...).
- DFS Pre-order: Root → Left → Right.
- DFS In-order: Left → Root → Right.
- DFS Post-order: Left → Right → Root.
Step-by-Step Breakdown
- Push Root to Queue.
- While Queue is not empty:
- Dequeue node and Visit it.
- Enqueue Left child (if exists).
- Enqueue Right child (if exists).
When to Use
- BFS: Finding shortest path in unweighted graphs/trees. Level-order printing.
- DFS: Pathfinding, topological sorting, solving puzzles (mazes).
- In-order: Getting sorted elements from a BST.
When NOT to Use
- BFS: When tree is very wide (high memory usage for queue).
- DFS: When tree is very deep (stack overflow risk).
How to Identify
Keywords: "Level order", "Shortest path" (BFS), "Explore all paths", "Backtracking" (DFS).
Applying for software engineering roles? Free, no sign-up:
