Write a C program to insert and delete elements in the Binary Search Tree.


Q.) Write a C program to insert and delete elements in the Binary Search Tree.

Subject: data structures
#include 
#include 

// Create a node
struct Node {
    int data;
    struct Node *left;
    struct Node *right;
};

// Function to insert a node
struct Node* insert(struct Node *root, int data) {
    // If the tree is empty, create a new node
    if (root == NULL) {
        struct Node *new_node = (struct Node*)malloc(sizeof(struct Node));
        new_node->data = data;
        new_node->left = NULL;
        new_node->right = NULL;
        return new_node;
    }

    // Otherwise, recurse down the tree
    if (data < root->data) {
        root->left = insert(root->left, data);
    } else {
        root->right = insert(root->right, data);
    }

    return root;
}

// Function to delete a node
struct Node* delete(struct Node *root, int data) {
    // If the tree is empty, return NULL
    if (root == NULL) {
        return NULL;
    }

    // Otherwise, recurse down the tree
    if (data < root->data) {
        root->left = delete(root->left, data);
    } else if (data > root->data) {
        root->right = delete(root->right, data);
    } else {
        // If the node has no children, simply delete it
        if (root->left == NULL && root->right == NULL) {
            free(root);
            return NULL;
        }

        // If the node has one child, replace it with its child
        else if (root->left == NULL) {
            struct Node *temp = root->right;
            free(root);
            return temp;
        } else if (root->right == NULL) {
            struct Node *temp = root->