Article 86 - Data Structure - Tree - Preorder vs Postorder vs Inorder

Tree traversal is a popular topic in technical interview questions. Perfecting or mastering these techniques will definitely be to your advantage.

There are differences in the three types of tree traversals, each having a distinct purpose and real world application. We must understand how each type of traversal works.

Implementation

The structure of a binary tree node.

typedef struct Node {
    struct Node * leftChild;
    struct Node * rightChild;
    int content;
} Node;

Preorder

This form of tree traversal visits the current nodes before visiting either of the child or grand child nodes.

A function that performs preorder traversal.

void preorder( Node * tree ){
    if( !tree ){
        return;
    }

    tree->content;

    preorder( tree->leftChild );
    preorder( tree->rightChild );
}

Postorder

This form of tree traversal visits the child and all grand child nodes before visiting the current node.

A function that performs postorder traversal.

void postorder( Node * tree ){
    if( !tree ){
        return;
    }

    preorder( tree->leftChild );
    preorder( tree->rightChild );

    tree->content;
}

Inorder

This form of tree traversal visits one side of child node and all of the grand child nodes in that side before visiting the current node and then finally visiting all the child and grand child nodes on the other side.

A function that performs inorder traversal.

void inorder( Node * tree ){
    if( !tree ){
        return;
    }

    preorder( tree->leftChild );

    tree->content;

    preorder( tree->rightChild );
}

Comments (5)

Posted by anonymous - bookmarks at Thursday, March 14, 2013 10:24 PM

P0LI3E Thanks for the blog article.Thanks Again. Really Great.

Posted by anonymous - ciprofloxacin side effects at Friday, March 15, 2013 10:52 AM

Appreciate you sharing, great article.Really thank you! Keep writing.

Posted by anonymous - generic viagra no prescription at Friday, March 15, 2013 12:31 PM

I really like and appreciate your blog article.Thanks Again. Great.

Posted by anonymous - cialis online at Friday, March 15, 2013 2:10 PM

I think this is a real great blog article.Thanks Again. Cool.

Posted by anonymous - Buy Levitra online at Friday, March 15, 2013 3:51 PM

Im obliged for the blog post.Much thanks again. Fantastic.

Post a comment

  • Name:
  • Post:
  • Challenge:

Register or login to post comments easier.


Vantasy World Copyright 2011 - 2017. Vantasy World is a project developed by Vantasy Online. Privacy Policy.