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 single linear way.

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

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

So let’s talk about all form of depth-first traversal i.e inorder, preorder and postorder.

Inorder Traversal

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

In this approach, we first go the left subtree of the tree then back to the root and after that to the right subtree of the tree.

Preorder Traversal

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

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

Preorder Traversal

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

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

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) so with recursion, we can easily treat each node as the root of the underlying subtree.

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

tree traversals

Java

C++

Output

In the above program, we have used the node as a class and inserted values (other nodes) using the root node. By doing this we form a Binary tree, then traversed it using the tree traversal method.

If you have any doubts or suggestion then comment below.

Leave a Reply

Close Menu