There are many different types of graph traversal algorithms that compute info over graphs
eg: The above tree can be traversed in various ways to get infix, postfix and prefix expressions:
PreFix(node)
if (node != empty) then
output name(node)
PreFix(left(node))
PreFix(right(node))
PostFix(node)
if (node != empty) then
PostFix(left(node))
PostFix(right(node))
output name(node)
InFix(node)
if (node != empty) then
InFix(left(node))
output name(node)
InFix(right(node))
note: all these functions are recursive (the call stack is used to "remember" the previous state of the functions) this is another form of backtracking
A more general form of graph traversal utilizing backtracking is constructed using a stack based algorithm:
the visited Boolean array is used to determine if the traversal has already reached a particular node
This particular graph algorithm is called: Depth-First Search (DFS) it explores as deep as possible into a graph first, then backtracks to all the possible alternatives at each node
DFS is used in more complex algorithms to apply orderings to nodes (called a topological sort), or to find out how strongly connected a graph is
variants of DFS are also used in artificial intelligence (AI) for computing over search spaces, (eg. using a DFS-based algorithm, program can compute next chess move)
in the binary tree above, with the root node as the start node, the following order of traversalis achieved by DFS:
Traversal Order of DFS(a) = {a, b, d, e, c, f, h, i, g}
in the 5-node 7-edge graph above, the following order of traversal is achieved by DFS:
DFS(A) = {A, B, C, E, D}
If we substitute a queue for the stack in the above algorithm, all adjacent nodes are explored first this variant explores a level at a time with no backtracking!
the algorithm is called: Breadth-first Search (BFS)
BFS is used in more complex graph algorithms for finding the shortest paths in a graph with edge values ("weights") – this is a critical algorithm for the internet (to find the fastest way to connect your computer to a remote computer...)