Learning Tree Traversal
Tree traversal is a classic computer science problem. The idea is to visit every single node in the tree once, regardless of the shape or specific type of tree. There are many ways of doing it, and each can be good in different situations. This is much different from a Linked List, Stack, or Queue, where there is really just one way of visiting every node, and that is to go from the beginning to the end in a linear manner.
There are two main ways of traversing a tree. The first is called Breadth-First Search(BFS), and the second is called Depth-First Search(DFS). BFS works “across” the tree, visiting each nodes siblings before moving on to their children, while DFS visits a node’s child nodes before its sibling nodes. They both have the same time complexity, but sometimes one will be better than the other depending on the specific scenario.
BFS starts by visiting the root node, then going to the next level below from left to right. Once it visits the sibling node that is furthest on the right of a level, it goes to the next level and repeats the process until all nodes have been visited. In order to know which node to visit once it needs to go down a level in the tree, a BFS algorithm has to store nodes in a queue or array. This means that on particularly wide trees, BFS is not a great choice since so many nodes have to be stored in memory. In the example below, I wrote a BFS algorithm using an array instead of a queue for simplicity’s sake, although a queue would be more performant.
There are some situations where BFS performs well. For example, if we are traversing a tree where each node only has one child, only one node needs to be stored in the queue at once, so not too much memory will be needed.
There are a few variants of DFS, but one thing that they have in common is that all of them visit a node’s children before it’s siblings. The main variants are called Inorder, Preorder, and Postorder.
Inorder visits nodes in order of ascending value, which can be useful if you need the data to be returned sorted in that manner.
Preorder visits the root, then descends down the left side of the tree before moving over to the right side.
Postorder visits the node at the bottom left of the tree, it’s siblings, and then moves up towards the parents. Once the left side of the tree has been visited, it visits the bottom right and repeats the same process as on the left. Finally, it goes back and visits the root node last.