Solved programming problem

Implement Binary Search Tree with Linked List in C++.

Source code

#include <iostream>

using namespace std;

struct list

{

    int data;

    struct list *right,*left;

};

typedef struct list node;

node *root =NULL;

void insert_bst(node *root,node *temp)

{

    if(temp->data >= root->data)

    {

        if(root->right==NULL)

        {

            root->right=temp;

            return;

        }

        else

        {

            insert_bst(root->right,temp);

        }

    }

    else

    {

        if(root->left==NULL)

        {

            root->left=temp;

            return;

        }

        else

        {

            insert_bst(root->left,temp);

        }

    }

}

void print(node *temp)

{

    if (temp != NULL)

    {

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

        print(temp->left);

        print(temp->right);

    }

}

int main()

{

    int n,flag=1;

    while(flag==1)

    {

        cout<<"Press 1 to Insert Value 0 to Exit: ";

        cin>>flag;

        if(flag!=1) break;

        cout<<"Value: ";

        cin>>n;

        if(root==NULL)

        {

            root = new node();

            root ->data =n;

            root->right =root->left=NULL;

        }

        else

        {

            node *temp = new node();

            temp ->data =n;

            temp->right =temp->left=NULL;

            insert_bst(root,temp);

        }

    }

    cout<<"B S T: 
";

    print(root);

    cout<<endl;

    return 0;

}

Output

Press 1 to Insert Value 0 to Exit: 1
Value: 10
Press 1 to Insert Value 0 to Exit: 1
Value: 5
Press 1 to Insert Value 0 to Exit: 1
Value: 50
Press 1 to Insert Value 0 to Exit: 1
Value: 3
Press 1 to Insert Value 0 to Exit: 1
Value: 12
Press 1 to Insert Value 0 to Exit: 0
B S T:
10 5 3 50 12

 

Join the discussion

Add your comment