Tuesday, 20 October 2015

Implement Binary Search Tree in C

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>

struct node{
    int data;
    struct node *left;
    struct node *right;
};

void minValue(struct node *root){
    if(root==NULL){
        printf("\nCan't find Min. Value ,  Empty Tree\n");
    }
    while(root->left!=NULL){
        root=root->left;
    }
    printf("Min Value = %d",root->data);
}


void maxValue(struct node *root){
    if(root == NULL){
        printf("\nCan't find Max. Value , Empty Tree\n");
    }
    while(root->right!=NULL){
        root=root->right;
    }
    printf("Max value = %d",root->data);
}


struct node *rightinsert(int data, struct node *root)
{
    struct node *temp=NULL;
    printf("Entered the right insert loop\n");
    if(root==NULL){
        temp = (struct node *)malloc(sizeof(struct node));
        if(temp==NULL){
            printf("Out of Space !! \n");
        }
        else{
            temp->data=data;
            temp->right=temp->left =NULL;
        }
    return temp;
    }
    else if(root->data>data){
        printf("entering to the left\n");
        root->left = rightinsert(data,root->left);
    }
    else if(root->data<data){
        printf("entering to the right\n");
        root->right = rightinsert(data,root->right);
    }
    else{
        printf("Element exist in the tree\n");
    }
    return root;
}

struct node *insert(struct node *root){
    int data;
    printf("Enter the data to be inserted\n");
    scanf("%d",&data);
    root=rightinsert(data,root);
    //free(temp);
    printf("printing root after insert operation\n");
    printf("%d\t",root->data);
    return root;
}

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

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

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

int main()
{
    struct node *root =NULL;
    int i=0;
    for(i=0;i<10;i++){
    root=insert(root);
    }
    printf("\nInorder Representation \n");
    root=inorder(root);   
    printf("\nPreorder Representation \n");
    root=preorder(root);
    printf("\nPostOrder Representation \n");
    root=postorder(root);
    printf("\n\n");

    printf("\nFind Min Value in tree\n");
    minValue(root);
    printf("\nFInd Max Value in tree\n");
    maxValue(root);
   
    printf("\n\n");
   
return 0;
}

No comments:

Post a Comment