BST_INSERT
BST_INSERT
h>
#include <stdlib.h>
// structure of a node
struct node
{
int data;
struct node *left;
struct node *right;
};
return new_node;
}
if (new_node != NULL)
{
// if the root is empty then make a new node as the root node
if (root == NULL)
{
root = new_node;
printf("\n Node having data %d is inserted\n", data);
return;
}
// traverse through the BST to get the correct position for insertion
while (temp != NULL)
{
prev = temp;
if (data > temp->data)
{
temp = temp->right;
}
else
{
temp = temp->left;
}
}
// found the last node where the new node should insert
if (data > prev->data)
{
prev->right = new_node;
}
else
{
prev->left = new_node;
}
else
{
//leaf node
if(root->left == NULL && root->right == NULL)
{
root=NULL;
free(root);
}
//right child
else if (root->left == NULL)
{
struct node *temp = root->right;
free(root);
return temp;
}
//left child
else if (root->right == NULL)
{
struct node *temp = root->left;
free(root);
return temp;
}
struct node *temp = smallest_node(root->right);
root->data = temp->data;
root->right = delete (root->right, temp->data);
}
return root;
}
// search the given key node in BST
int search(int key)
{
struct node *temp = root;
while (temp != NULL)
{
if (key == temp->data)
return 1;
else if (key > temp->data)
temp = temp->right;
else
temp = temp->left;
}
return 0;
}
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
int main()
{
int choice;
struct node* result = NULL;
while (1)
{
printf("\n\n------- Binary Search Tree ------\n");
printf("\n1. Insert");
printf("\n2. Delete");
printf("\n3. Search");
printf("\n5. Exit");
switch(choice)
{
case 1:
printf("\nEnter Data to be inserted : ");
scanf("%d", &data);
insert(data);
break;
case 2:
if (root == NULL)
printf("\n Tree is empty\n");
else{
case 3:
printf("\nEnter Data to be searched : ");
scanf("%d", &data);
if (search(data) == 1)
printf("\nData is found!\n");
else
printf("\nData is not found!\n");
break;
case 4:
inorder(root);
break;
case 5:
printf("\n\nThank you!!\n");
break;
default:
printf("\n\tInvalid Choice\n");
break;
}
}
return 0;
}