Tree Traversal

 

Tree: Tree is non linear data structure.
    1. Rooted at one vertex.
    2. Tree contains no cycle.
    3. Elements are arranged in layers.
    4. A unique path travers from root to any node.

Tree Traversals (Inorder, Preorder and Postorder)

 

Unlikelinear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. Following are the generally used ways for traversing trees.





 

Depth First Traversals: 


(a) Inorder (Left, Root, Right) : 4 2 5 1 3 
(b) Preorder (Root, Left, Right) : 1 2 4 5 3 
(c) Postorder (Left, Right, Root) : 4 5 2 3 1

Inorder Traversal: Inorder (Left, Root, Right) :

Algorithm Inorder(tree)

   1. Traverse the left subtree.

   2. Visit the root.

   3. Traverse the right subtree.

Uses of Inorder :


In case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order. To get nodes of  BST in non-increasing order, a variation of Inorder traversal where Inorder traversal s reversed can be used. 
Example: Inorder traversal for the above-given figure is 4 2 5 1 3.


Preorder Traversal : Preorder (Root, Left, Right) :

Algorithm Preorder(tree):

   1. Visit the root.

   2. Traverse the left subtree. 

   3. Traverse the right subtree.

Uses of Preorder 

Preorder traversal is used to create a copy of the tree. Preorder traversal is also used to get prefix expression on of an expression tree.

Example: Preorder traversal for the above given figure is 1 2 4 5 3.

 

Postorder Traversal Postorder (Left, Right, Root)

Algorithm Postorder(tree):

   1. Traverse the left subtree. 

   2. Traverse the right subtree.

   3. Visit the root.

Uses of Postorder :
Postorder traversal is used to delete the tree. Postorder traversal is also useful to get the postfix expression of an expression tree. Example: Postorder traversal for the above given figure is 4 5 2 3 1.

 I have a related video in my youtube channel: Engineers voice bd




Comments