SYBCom(CA) DS Practical Slip 12 Q.B

Write a C Program to implement the following functions on Binary Search Tree
-To insert a new element in the tree
-To search an element in a tree and give the proper message.

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

// Structure of a BST node
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

// Function to create a new node
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;
}

// Function to insert a node in BST
struct Node* insert(struct Node* root, int data) {
    if (root == NULL)
        return createNode(data);

    if (data < root->data)
        root->left = insert(root->left, data);
    else if (data > root->data)
        root->right = insert(root->right, data);

    return root;
}

// Function to search a node in BST
int search(struct Node* root, int key) {
    if (root == NULL)
        return 0;  // Not found

    if (root->data == key)
        return 1;  // Found

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

// Main function
int main() {
    struct Node* root = NULL;
    int n, value, key;

    printf("Enter number of elements to insert in BST: ");
    scanf("%d", &n);

    printf("Enter %d elements:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &value);
        root = insert(root, value);
    }

    printf("Enter element to search: ");
    scanf("%d", &key);

    if (search(root, key))
        printf("Element %d is present in the BST.\n", key);
    else
        printf("Element %d is NOT present in the BST.\n", key);

    return 0;
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top