Browse curriculum

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.

10

 

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

BFS Algorithm:
  1. Push Root to Queue.
  2. While Queue is not empty:
  3. Dequeue node and Visit it.
  4. Enqueue Left child (if exists).
  5. 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:

AI resume checker — match your resume to the job description

Frequently Asked Questions

What is In-order traversal useful for?

For a Binary Search Tree, In-order traversal visits nodes in ascending (sorted) order.


Pre-order vs Post-order?

Pre-order (Root-Left-Right) is great for cloning trees. Post-order (Left-Right-Root) is ideal for deleting trees or evaluating postfix expressions.


What is BFS/Level-order?

Breadth-First Search visits all nodes at one level before moving down to the next, typically using a Queue.