Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- typedef struct node * BST;
- struct node
- {
- struct node *leftChild;
- int data;
- struct node *rightChild;
- };
- BST temp=NULL, ptr=NULL, root=NULL, prev=NULL;
- BST newNode()
- {
- BST X;
- X=(struct node *)malloc(sizeof(struct node));
- X->leftChild=X->rightChild=NULL;
- return X;
- }
- void createBST(int elem)
- {
- temp=newNode();
- temp->data=elem;
- if(!root)
- root=temp;
- else
- {
- prev=NULL;
- ptr=root;
- while(ptr)
- {
- prev=ptr;
- ptr=(ptr->data<temp->data)?ptr->rightChild:ptr->leftChild;
- if(prev->data==elem) // remove duplicate entries
- {
- free(temp);
- return;
- }
- }
- if(prev->data<temp->data)
- prev->rightChild=temp;
- else if(prev->data>temp->data)
- prev->leftChild=temp;
- }
- }
- void inOrder(BST ptr)
- {
- if(ptr)
- {
- inOrder(ptr->leftChild);
- printf("%d ",ptr->data);
- inOrder(ptr->rightChild);
- }
- }
- void preOrder(BST ptr)
- {
- if(ptr)
- {
- printf("%d ",ptr->data);
- preOrder(ptr->leftChild);
- preOrder(ptr->rightChild);
- }
- }
- void postOrder(BST ptr)
- {
- if(ptr)
- {
- postOrder(ptr->leftChild);
- postOrder(ptr->rightChild);
- printf("%d ",ptr->data);
- }
- }
- void traverBST()
- {
- if(!root)
- {
- printf("\nThe Binary Search Tree is empty\n");
- return;
- }
- printf("\nThe inorder traversal of the entered BST is: ");
- inOrder(root);
- printf("\nThe preorder traversal of the entered BST is: ");
- preOrder(root);
- printf("\nThe postorder traversal of the entered BST is: ");
- postOrder(root);
- printf("\n");
- }
- void searchBST()
- {
- if(!root)
- {
- printf("\nThe Binary Search Tree is empty\n");
- return;
- }
- int KEY;
- printf("\nEnter the KEY Element to be searched: ");
- scanf("%d",&KEY);
- ptr=root;
- while(ptr)
- {
- if(ptr->data==KEY)
- {
- printf("\nThe KEY %d is present in the entered BST\n",KEY);
- return;
- }
- ptr=(ptr->data<KEY)?ptr->rightChild:ptr->leftChild;
- }
- printf("\nThe KEY %d is not present in the enterd BST\n",KEY);
- }
- void exitProgram()
- {
- printf("\nThank you for using the program");
- exit(0);
- }
- int main()
- {
- int choice;
- while(1)
- {
- printf("\nPick a Binary Search Tree operation\n1) Create a Binary Search Tree\n2) Traverse the Binary Search Tree\n3) Seach for a KEY element in the Binary Search Tree\n4) Exit\n>| ");
- scanf("%d",&choice);
- switch(choice)
- {
- case 1:
- {
- int num,elem;
- printf("\nEnter the number of elements to be inserted into the Binary Search Tree: ");
- scanf("%d",&num);
- printf("\nEnter the elements to be inserted into the Binary Search Tree: ");
- for(int i=1;i<=num;i++)
- {
- scanf("%d",&elem);
- createBST(elem);
- }
- }
- break;
- case 2:
- traverBST();
- break;
- case 3:
- searchBST();
- break;
- case 4:
- exitProgram();
- break;
- default:
- printf("\nInvalid Choice\n");
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement