Binary Tree Traversal - Preorder , inorder , postorder with codes

 Binary Tree Traversal

1) Traversal is the process of visiting every node at least once

2)Visiting a node involves doing some processing at that node, but when describing

a traversal strategy, we need not concern ourselves with what that processing is Three recursive techniques for binary tree traversal

3)In each technique, the left subtree is traversed recursively, the right subtree is

traversed recursively, and the root is visited

4)What distinguishes the techniques from one another is the order of those 3 tasks


Preoder, Inorder, Postorder

 

1)In Preorder, the root is visited before (pre) the subtrees traversals

2)In Inorder, the root is visited in-between left and right subtree traversal

3)In Preorder, the root is visited after (pre) the subtrees traversals 

                          

    ILLUSTRATIONS FOR TRAVERSALS 

           

Code for the Traversal Techniques

1) Preorder: 

void preOrder(Tree *tree){

if (tree->isEmpty( )) return;

visit(tree->getRoot( ));

preOrder(tree->getLeftSubtree());

preOrder(tree->getRightSubtree());


2) Inorder: 

void inOrder(Tree *tree){

if (tree->isEmpty( )) return;

inOrder(tree->getLeftSubtree( ));

visit(tree->getRoot( ));

inOrder(tree->getRightSubtree( ));

}


3)Postorder

if (tree->isEmpty( )) return;

postOrder(tree->getLeftSubtree( ));

postOrder(tree->getRightSubtree( ));

visit(tree->getRoot( ));}

Post a Comment

Previous Post Next Post