Program for binary search tree in C

In binary search tree,

The first number that we insert is the root element and every other number that is entered in the binary search tree is compared with the root element.

If the new number is > the root element then it is put in the right sub-tree.

And if new number is < the root element then it is put in the left sub-tree.

 

Program:

#include<stdio.h>
#include<malloc.h>
struct node
{
    int data;
    struct node *left;
    struct node *right;
};
struct node *r;
struct node* insert(struct node*,int val);
void preorder(struct node *);
void inorder(struct node *);
void postorder(struct node *);
int main()
{
    r=NULL;
    int i,a,b=1,n;
    printf("Enter the number of values you wanna insert in binary search tree.\n");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        printf("Enter the value %d:",i+1);
        scanf("%d",&a);
        r=insert(r,a);
    }
    while(b)
    {
    printf("In which format do you want to display it?\n1. Preorder\n2. Inorder\n3. Postorder");
    scanf("%d",&n);
    switch(n)
    {
    case 1:
        {
            preorder(r);
            break;
        }
    case 2:
        {
            inorder(r);
            break;
        }
    case 3:
        {
            postorder(r);
            break;
        }
    default:
        printf("Not a valid option.\n");
    }
    printf("Continue? 1/0\n");
    scanf("%d",&b);
    }
}

struct node* insert(struct node *r,int val)
{
    if(r==NULL)
    {
        r=(struct node*) malloc(sizeof(struct node));
        r->data=val;
        r->left=NULL;
        r->right=NULL;
    }
    else if(val>r->data)
    {
        r->right=insert(r->right,val);
    }
    else
    {
        r->left=insert(r->left,val);
    }
    return r;
};

void preorder(struct node *r)
{
    if(r!=NULL)
    {
    printf("%d\t",r->data);
    preorder(r->left);
    preorder(r->right);
}
}
void inorder(struct node *r)
{
if(r!=NULL)
{
    inorder(r->left);
    printf("%d\t",r->data);
    inorder(r->right);
}
}

void postorder(struct node *r)
{
    if(r!=NULL)
    {
    postorder(r->left);
    postorder(r->right);
    printf("%d\t",r->data);
}
}

 

Leave a Reply

Your email address will not be published.