Search BST

PHOTO EMBED

Thu May 25 2023 16:07:23 GMT+0000 (Coordinated Universal Time)

Saved by @prachi

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

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

struct node* createNode(int data) {
    struct node* newNode = (struct node*)malloc(sizeof(struct node));
    newNode->data = data;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

struct node* insertNode(struct node* root, int data) {
    if (root == NULL) {
        return createNode(data);
    }

    if (data < root->data) {
        root->left = insertNode(root->left, data);
    } else if (data > root->data) {
        root->right = insertNode(root->right, data);
    }

    return root;
}

struct node* search(struct node* root, int key) {
    if (root == NULL || root->data == key) {
        return root;
    }

    if (key < root->data) {
        return search(root->left, key);
    }

    return search(root->right, key);
}

int main() {
    struct node* root = NULL;
    int choice, data, key;
    struct node* foundNode;

    while (1) {
        printf("Binary Search Tree Operations:\n");
        printf("1. Insert Element\n");
        printf("2. Search Element\n");
        printf("3. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                printf("Enter the element to insert: ");
                scanf("%d", &data);
                root = insertNode(root, data);
                printf("Element inserted successfully.\n");
                break;
                break;
            case 2:
                printf("Enter the element to search: ");
                scanf("%d", &key);
                foundNode = search(root, key);
                if (foundNode != NULL) {
                    printf("Element found: %d\n", foundNode->data);
                } else {
                    printf("Element not found.\n");
                }
                break;
            case 3:
                printf("Exiting...\n");
                exit(0);
            default:
                printf("Invalid choice! Please enter a valid option.\n");
        }
        printf("\n");
    }

    return 0;
}
content_copyCOPY