Professional Documents
Culture Documents
C Program To Demonstrate BST Operations - Lab 10: Stdio.h Stdlib.h
C Program To Demonstrate BST Operations - Lab 10: Stdio.h Stdlib.h
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node *root;
void initialize()
{
root=NULL;
}
void insert(int ele)
{
struct node *temp = (struct node*) malloc(sizeof(struct node));
struct node *current, *parent;
temp -> data = ele;
temp -> left = NULL;
temp -> right = NULL;
if(root == NULL) //if binary search tree is empty, make temp as the root
node
root = temp;
else //When BST is not empty, the following code executes
{
current = root;
parent = NULL;
while(1)
{
parent = current;
if(ele < parent -> data) //go to left of the tree
{
current = current -> left;
if(current == NULL) //insert to the left
{
parent -> left = temp;
return;
} // end of inner if
} //end of outer if
else
{
current = current -> right; //go to right of the tree
else if(key < temp -> data) // Search in the left sub tree.
return search(temp -> left, key);
else // Element Found
return temp;
}
int main()
{
initialize();
int choice, ele;
struct node *found;
do
{
printf("\nBinary Search Tree Operations");
printf("\n1.Insert an element into the binary search tree");
printf("\n2.InOrder traversal");
printf("\n3.PreOrder traversal");
printf("\n4.PostOrder traversal");
printf("\n5.Search a key in the Binary Search Tree");
printf("\n6.Exit");
printf("\nEnter your choice: (1-6) ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("\nEnter the value to be inserted into the
Binary Search Tree: ");
scanf("%d", &ele);
insert(ele);
break;
case 2:
printf("\nInorder Traversal is: ");
inorder(root);
break;
case 3:
printf("\nPreorder Traversal is: ");
preorder(root);
break;
case 4:
printf("\nPostorder Traversal is: ");
postorder(root);
break;
case 5:
printf("\nEnter the key to be searched: ");
scanf("%d", &ele);
found = search(root, ele);
printf("\n %d is found", found -> data);
break;
case 6:
exit(0);
}//end switch
}while(choice != 6);
return 0;
}