Logo 
Search:

C++ Programming Articles

Submit Article
Home » Articles » C++ Programming » Data File StructureRSS Feeds

Program of traversing a binary tree in inorder, preorder and postorder fashion

Posted By: Emily Campbell     Category: C++ Programming     Views: 19095

Program of traversing a binary tree in inorder, preorder and postorder fashion.

Code for Program of traversing a binary tree in inorder, preorder and postorder fashion in C++ Programming

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
struct btree
{
    struct btree *left;
    struct btree *right;
    int no;
};
void postorder(struct btree *trav);
void inorder(struct btree *trav);
void preorder(struct btree *trav);
struct btree * create(struct btree *trav);
main()
{
    struct btree *root=NULL;
    char c;
    clrscr();
    while(1)
    {
        root=create(root);
        cout<<"Do you want to continue : ";
        cin>>c;
        if(c=='n' ||c=='N')
            break;
    }
    cout<<endl<<"Inoder is    : ";inorder(root);
    cout<<endl<<"Preorder is  : ";preorder(root);
    cout<<endl<<"Postorder is : ";postorder(root);
    getch();
}
struct btree * create(struct btree *trav)
{
    if(trav==NULL)
    {
        trav=new btree;
        trav->right=NULL;
        trav->left=NULL;
        cout<<"Enter the no : ";
        cin>>trav->no;
        return(trav);
    }
    char choice;
    cout<<"Enter the left or right child : ";
    cin>>choice;
    if(choice == 'r' || choice == 'R')
    {
        trav->right=create(trav->right);
    }
    if(choice=='l' || choice=='L')
    {
        trav->left=create(trav->left);
    }
    return(trav);
}
void inorder(struct btree *trav)
{
    if(trav==NULL)
        return ;
    inorder(trav->left);
    cout<<" "<<trav->no;
    inorder(trav->right);
}
void preorder(struct btree *trav)
{
    if(trav==NULL)
        return;
    cout<<" "<<trav->no;
    preorder(trav->left);
    preorder(trav->right);
}
void postorder(struct btree *trav)
{
    if(trav==NULL)
        return;
    postorder(trav->left);
    postorder(trav->right);
    cout<<" "<<trav->no;
}
  
Share: 



Emily Campbell
Emily Campbell author of Program of traversing a binary tree in inorder, preorder and postorder fashion is from Toronto, Canada.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!