×
By the end of this chapter you should be able to:
Now that we have figured out how to insert values into our Binary Search Tree (BST) and find values, what would happen if we wanted to find every single value in the BST? For traversing through all of the nodes in a BST, there are two common algorithms that we use, which enable us to only have to visit each node once. These two algorithms are called Depth First Search (DFS) and Breadth First Search (BFS). They each utilize a secondary data structure (a stack for DFS and a queue for BFS) in order to traverse the tree.
The algorithm behind depth first search is to search via "depth" and explore each branch of the tree as much as possible. But then the question arises, at which node do we start? Do we start at the root? Do we start at the leftmost node and go upward? Or do we start at the leftmost node and then find the next deepest left node? These distinctions might seem confusing right now, but the difference between them will be clear in a moment. These three approaches to performing depth first search have different names: pre-order, in-order, and post-order.
With pre-order, the algorithm is as follows:
In the above example, starting at the root node, we would capture the values in this order: F, B, A, D, C, E, G, I, H.
With in-order, the algorithm is as follows:
In the above example, starting at the root node, we would capture the values in this order: A, B, C, D, E, F, G, H, I. Hence the name: the letters are in order!
With post-order, the algorithm is as follows:
In the above example, starting at the root node, we would capture the values in this order: A, C, E, D, B, H, I, G, F.
We can see that the implementation of these three kinds of DFS are very similar. The pseudocode is the same, just in a different order! Indeed, once you implement one of these algorithms, you can implement the rest just by changing the order of code!
The other alternative to traversing is to search horizontally, or through the "breadth" of the tree. The algorithm is as follows:
In the above example, starting at the root node, we would capture the values in this order: F, B, G, A, D, I, C, E, H.
For more on tree traversal, including references to the traversal images shown here, check out this article.
Complete Part II of the exercises here.
When you're ready, move on to Binary Search Trees - Removal