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);
}
}

 

Entering data in file using file handling in C [Program]

#include <stdio.h>
main( )
{
     FILE *fp;
     char material[1000];

     fp = fopen("material.txt","w"); /* open for writing */
     printf("Enter the material to be written in the text file.\n");
     gets(material); /* For including spaces we use gets function here! */
     fprintf(fp,"%s", material);
     fclose(fp); /* close the file before ending program to ensure no errors in extreme case.. */
}

 

 

Output:

A file named material.txt will be creasted automatcially in the location where your .c file is present.

Here are the screenshots:

1.1 1.2 1.3