Data Structures and Algorithms - Old Questions

10. Differentiate between pre-order traversal and in order traversal.

5 marks | Asked in 2074

Pre-order Traversal 

In Pre-Order traversal, the root node is visited before left child and right child nodes. In this traversal, the root node is visited first, then its left child and later its right child. This pre-order traversal is applicable for every root node of all subtrees in the tree.

Algorithm:

Until all nodes are traversed:-

Step 1: Visit root node

Step 2: Recursively traverse left sub-tree.

Step 3: Recursively traverse right sub-tree.

.

E.g.


The preorder traversal output of the given above tree is: A B D H I E C F G


In-order Traversal:

In In-Order traversal, the root node is visited between left child and right child. In this traversal, the left child node is visited first, then the root node is visited and later we go for visiting right child node. This in-order traversal is applicable for every root node of all subtrees in the tree. This is performed recursively for all nodes in the tree

Algorithm:

Until all nodes are traversed:-

Step 1: Recursively traverse left sub-tree.

Step 2: Visit root node

Step 3: Recursively traverse right sub-tree.

E.g.

The inorder traversal output of the given tree is: H D I B E A F C G