Traversing trees

Traversing means visiting the nodes of a tree. There are three ways of traversing a binary tree: preorder, inorder, and postorder. Since traversing a binary tree requires visiting the root and then its left and right child, these three ways of traversal only differ in the order in which visiting is performed. The tree traversal methods that are defined with the recursion method are as follows:

For preorder traversal, these are the steps:

  1. Visit the root
  2. Traverse the left subtree in preorder
  3. Traverse the right subtree in preorder
In preorder traversal, the root node of the binary tree is visited first.

For inorder traversal, these are the steps:

  1. Traverse the left subtree in inorder
  2. Visit the root
  3. Traverse the right subtree in inorder

For postorder traversal, these are the steps:

  1. Traverse the left subtree in postorder
  2. Traverse the right subtree in postorder

Now that we've had a thorough introduction to the structures we will be looking at in this chapter, we can begin our journey.