What does it mean to traverse a graph, and why must a graph traversal mark what it has visited when a tree traversal need not?
A traversal visits every vertex and every edge of a graph in a systematic order. A graph can contain cycles and several paths to the same vertex, so the traversal labels each vertex and edge once it has dealt with it; without these marks it would reach vertices again and again, and run around a cycle forever.
In a rooted tree there is exactly one path from the root to each node, so following the child links reaches every node exactly once and needs no bookkeeping. A graph gives up both guarantees. In the triangle A–B–C, the walk A, B, C arrives back at A and would go round indefinitely, and in most graphs a vertex can be reached along many different routes.
A file system shows the difference. Its directories form a tree, until a symbolic link points back to a parent directory: then the tree has become a graph with a cycle, and a tool that follows links, such as find -L, has to remember which directories it has entered. GNU find stops at such a link with the message "File system loop detected".
The labels make the walk finite. Every vertex starts as UNEXPLORED and becomes VISITED the first time it is reached; every edge starts as UNEXPLORED and receives its final label as soon as it has been examined. A traversal never enters a VISITED vertex again and never examines a labelled edge again, so it does a constant amount of work per vertex and per edge.
Two traversal orders are standard, and both run in $O(n + m)$ time for $n$ vertices and $m$ edges:
- Depth-first search (DFS) follows one path as deep as it can and backs up only at a dead end.
- Breadth-first search (BFS) works outwards in rounds: first the start vertex's neighbours, then their neighbours, and so on.
Where the labels are kept is an implementation detail. A field in each vertex and edge object costs $O(1)$ per access, guaranteed. A map from vertex or edge to label, kept beside the graph, works like a luggage tag tied on with string: it is attached to the object without changing its class, and a hash map reads and writes it in $O(1)$ on average.
Go deeper:
Graph traversal: redundancy — why a graph traversal has to record which vertices it has explored, unlike a tree traversal.