Data Structure Slip No_5A

  

#include <stdio.h>

#include <stdlib.h>

 

struct Node

{

    int data;

    struct Node* left;

    struct Node* right;

};

 

typedef struct Node Node;

 

Node* createNode(int data)

{

    Node* newNode = (Node*)malloc(sizeof(Node));

    newNode->data = data;

    newNode->left = NULL;

    newNode->right = NULL;

    return newNode;

}

 

Node* insert(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;

}

 

 

void inorderTraversal(Node* root)

   {

    if (root == NULL)

   {

        return;

    }

   

    inorderTraversal(root->left);

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

    inorderTraversal(root->right);

}

 

void postorderTraversal(Node* root)

   {

    if (root == NULL)

    {

        return;

    }

   

    postorderTraversal(root->left);

    postorderTraversal(root->right);

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

}

 

int main()

{

    Node* root = NULL;

    int choice, value;

 

    while (1)

    {

        printf("\nMenu:\n");

        printf("1. Insert into BST\n");

        printf("2. Inorder Traversal\n");

        printf("3. Postorder Traversal\n");

        printf("4. Exit\n");

        printf("Enter your choice: ");

        scanf("%d", &choice);

 

    

 

   switch (choice)

  {

            case 1:

                printf("Enter value to insert: ");

                scanf("%d", &value);

                root = insert(root, value);

                break;

            case 2:

                printf("Inorder Traversal: ");

                inorderTraversal(root);

                printf("\n");

                break;

            case 3:

                printf("Postorder Traversal: ");

                postorderTraversal(root);

                printf("\n");

                break;

            case 4:

                printf("Exiting program.\n");

                exit(0);

            default:

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

        }

    }

    return 0;

}


Output:

Menu:

1. Insert into BST

2. Inorder Traversal

3. Postorder Traversal

4. Exit

Enter your choice: 1

Enter value to insert: 25

Menu:

1. Insert into BST

2. Inorder Traversal

3. Postorder Traversal

4. Exit

Enter your choice: 1

Enter value to insert: 4

Menu:

1. Insert into BST

2. Inorder Traversal

3. Postorder Traversal

4. Exit

Enter your choice: 1

Enter value to insert: 45

Menu:

1. Insert into BST

2. Inorder Traversal

3. Postorder Traversal

4. Exit

Enter your choice: 2

Inorder Traversal: 4 25 45 


Menu:

1. Insert into BST

2. Inorder Traversal

3. Postorder Traversal

4. Exit

Enter your choice: 3

Postorder Traversal: 4 45 25 


No comments:

Post a Comment