Data Structure Slip no-1_A

#include <stdio.h>

#include <stdlib.h>


// Structure for a Node in Binary Search Tree

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 into 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 display elements of BST (Inorder Traversal)

void display(struct Node* root) {

    if (root != NULL) {

        display(root->left);

        printf("%d ", root->data);

        display(root->right);

    }

}

void main() {

    struct Node* root = NULL;

    int choice, data;

    while (1) {

        printf("\nMenu:\n");

        printf("1. Create a Binary Search Tree\n");

        printf("2. Insert element in Binary Search Tree\n");

        printf("3. Display\n");

        printf("4. Exit\n");

        printf("Enter your choice: ");

        scanf("%d", &choice);

 

        switch (choice) {

            case 1:

                root = NULL;  // Reset the BST

                printf("Binary Search Tree created.\n");

                break;

            case 2:

                printf("Enter element to insert: ");

                scanf("%d", &data);

                root = insert(root, data);

                printf("Element inserted.\n");

                break;

            case 3:

                printf("BST elements: ");

                display(root);

                printf("\n");

                break;

            case 4:

                printf("Exiting the program.\n");

                exit(0);

            default:

                printf("Invalid choice. Please enter a valid option.\n");

        }

    }

  }

 


No comments:

Post a Comment