Solved programming problem

Print In-Order, Pre-Order and Post-Order a BST in C++.

Source code

#include <iostream>

using namespace std;

struct tree

{

    int data;

    struct tree *right,*left;

};

typedef struct tree node;

node *head =NULL;

node *insert_bst(node *&temp,int value) ///save the address in temp

{

    if(temp==NULL)

    {

        temp = new node();

        temp->data=value;

        temp->right=NULL;

        temp->left=NULL;

    }

    else if(temp->data <= value ) ///compare temp->data with value

    {

        insert_bst(temp->right,value); ///if the value is grater then temp->data

    }

    else

    {

        insert_bst(temp->left,value); ///if the value is smaller then temp->data

    }

}

void inorder(node *temp)

{

    if(temp==NULL)

    {

        return;

    }

    inorder(temp->left);

    cout<<temp->data<<" ";

    inorder(temp->right);

}

void preorder(node *temp)

{

    if(temp==NULL)

    {

        return;

    }

    cout<<temp->data<<" ";

    preorder(temp->left);

   preorder(temp->right);

}

void postorder(node *temp)

{

    if(temp==NULL)

    {

        return;

    }

    postorder(temp->left);

    postorder(temp->right);

    cout<<temp->data<<" ";

}

int main()

{

    int flag=1,n,value;

    while(flag==1)

    {

        cout<<"Press 1 for Insert Data 0 to Exit: ";

        cin>>n;

        if(n!=1) break;

        cout<<"Value: ";

        cin>>value;

        insert_bst(head,value);

    }

    cout<<"
Print In order: ";

    inorder(head);

    cout<<endl;

    cout<<"Print Pre order: ";

    preorder(head);

    cout<<endl;

    cout<<"Print Post order: ";

    postorder(head);

    cout<<endl;

    return 0;

}

Output

Press 1 for Insert Data 0 to Exit: 1
Value: 5
Press 1 for Insert Data 0 to Exit: 1
Value: 2
Press 1 for Insert Data 0 to Exit: 1
Value: 6
Press 1 for Insert Data 0 to Exit: 1
Value: 1
Press 1 for Insert Data 0 to Exit: 1
Value: 7
Press 1 for Insert Data 0 to Exit: 0

Print In order: 1 2 5 6 7
Print Pre order: 5 2 1 6 7
Print Post order: 1 2 7 6 5

Join the discussion

Add your comment