Skip to main content

Searching in BST

 




#include <stdio.h>
#include <stdlib.h>
struct treeN
{
    int data;
    struct treeN *left;
    struct treeN *right;
   
};

struct treeN *BSTcreate(struct treeN *root, int val)
{
    if(root == NULL){
        struct treeN *root = malloc(sizeof(struct treeN));
        root->data = val;
        root->left = NULL;
        root->right = NULL;
        return root;
    }
     if (val < root->data)
    {
        root->left = BSTcreate(root->left, val);
    }
    else
    {
        root->right = BSTcreate(root->right, val);
    }
    return root;
}

void inorder(struct treeN *root)
{
    if (root != NULL)
    {
        inorder(root->left);
        printf(" %d ", root->data);
        inorder(root->right);
    }
}
struct treeN *search(struct treeN *root,int find){
    if(root == NULL){
        return 0;
    }
    else if(find == root->data){
        return root;
    }
    else if(find<root->data){
        return search(root->left,find);
    }
    else{
        return search(root->right,find);
    }
}
int main()
{
   
    struct treeN *root = NULL;
    root = BSTcreate(root,43);
    BSTcreate(root,10);
    BSTcreate(root,79);
    BSTcreate(root,90);
    BSTcreate(root,12);
    BSTcreate(root,54);
    BSTcreate(root,11);
    BSTcreate(root,9);
    BSTcreate(root,50);
   
    int s;
    printf("Enter the Element you wanna find: ");
    scanf("%d",&s);
 
    // inorder(root);
    struct treeN *i = search(root,s);
    if(i!=NULL){
        printf("Element Found: %d ",i->data);
    }
    else{
        printf("Opps! Element Not Found");
    }
   
    return 0;
}


Comments