Tree Traversal
To traverse a data structure is to visit, or read, all of the structure's elements. In a linear data structure like an array, there are two traversal approaches:
- First to last (called forward-linear traversal), or
- last to first (backward-linear traversal).
Data structures like binary trees, however, are non-linear. And because they're non-linear, they have several traversal approaches:
-
Depth-first search (DFS) — traversing the tree by starting at the root, and exploring as far as possible along each branch before backtracing.
-
Breadth-first search (BFS) — traversing the tree by starting at the root, and exploring all nodes at the present level before moving to nodes at a subsequent level.
Both approaches have several sub-approaches:
- Depth-first search:
- preorder traversal
- inorder traversal
- postorder traversal
- Bread-first search:
- level/generational traversal and variations
We examine each of these traversal approaches in turn.