Tree Traversal
Overview
Tree traversal (also known as tree search and walking the tree) is a form of graph traversal and refers to the process of visiting (e.g. retrieving, updating, or deleting) each node in a tree data structure, exactly once. Such traversals are classified by the order in which the nodes are visited.
Types
Trees are mainly traversed in two ways:
- depth-first (DFS): the search tree is deepened as much as possible before going to the next sibiling.
- breadth-first (BFS): the search tree is broadened as much as possible before going to the next sibiling.
Other types
There are also tree traversal algorithms that classify as neither depth-first search nor breadth-first search.
One such algorithm is Monte Carlo tree search, which concentrates on analyzing the most promising moves, basing the expansion of the search tree on random sampling of the search space.
Data Structures for Tree Traversal
Traversing a tree involves iterating over all nodes in some manner. Because from a given node there is more than one possible next node (it is not a linear data structure), then, assuming sequential computation (not parallel), some nodes must be deferred—stored in some way for later visiting. This is often done via a stack (LIFO) or queue (FIFO).
Depth-first search is easily implemented via a stack, including recursively (via the call stack), while breadth-first search is easily implemented via a queue, including corecursively.