Summary: In this tutorial, we will learn what is Inorder, Preorder and Postorder traversal method and how to implement these methods in C++ and Java.

A Tree which is a hierarchical (non-linear) data structure can be traversed in multiple ways unlike the linear data structure eg array, linked list, etc which can be traversed only in a linear fashion.

The basic two ways using which we can traverse a tree are:

  1. Depth First Traversal
    • Inorder
    • Preorder
    • Postorder
  2. Breadth First Traversal

In-order, pre-order, and post-order are three forms of depth-first search traversal method i.e. each method explores as far as possible along each branch before backtracking.

So let’s see how they differ form each other in context of depth-first traversal.

Inorder Traversal

  1. Left subtree.
  2. Root.
  3. Right subtree.

In the Inorder Traversal method, we first visit the left subtree then the root and after that to the right subtree of the tree.

Preorder Traversal

  1. Root.
  2. Left subtree.
  3. Right subtree.

In the Preorder traversal method, we start from the root, then we go the left subtree and finally to the right subtree.

Preorder Traversal

  1. Left subtree.
  2. Right subtree.
  3. Root.

In the Postorder tree traversal method, we first visit the left subtree and then the right subtree and finally the root.

Trick: Whichever method you use always remember that the left subtree always comes before the right subtree.

tree traversals

To implement these traversal methods we will use recursion because each part of the tree whether left or right is itself a tree (i.e. subtree).

In recursion, we treat each node as the root of the underlying subtree.

Here is the implementation of Pre-order, In-order, and Post-order traversal in C++ and Java.

Java

C++

Output:

In the above program, we have implemented the node as a class and linked other nodes using the insert method on the root.

By doing this we formed a Binary tree, then traversed it using the tree traversal methods.

In this tutorial, we learned what In-order, Pre-order and Post-order traversal are and how to implement them in C++ and Java programming languages.

Leave a Reply