Home
DSA Visualizer
Data Structures
Tree Traversal
Tree Traversal Visualization
Tree traversal is the set of algorithms for visiting every node in a tree data structure. Step through it in the interactive Tree Traversal visualization below.
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 Tree Traversal 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.
Tree Traversal Visualization, Step by Step
- 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).
Practice it on interview problems
LeetCode problems solved with the Depth-First Search pattern, each with a step-by-step visualizer:
Applying for software engineering roles? Free, no sign-up:
AI resume checker: match your resume to the job description
Compare its cost with every other algorithm in the Big O cheat sheet.
