#include <stdio.h>
#include
<stdlib.h>
struct
Node
{
int data;
struct Node* left;
struct Node* right;
};
struct
Node* createNode(int value)
{
struct Node* newNode = (struct
Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct
Node* insert(struct Node* root, int value)
{
if (root == NULL)
{
return createNode(value);
}
if (value < root->data)
{
root->left = insert(root->left,
value);
}
else if (value > root->data)
{
root->right = insert(root->right,
value);
}
return root;
}
void
inorder(struct Node* root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
struct
Node* findMin(struct Node* node)
{
while (node->left != NULL)
{
node = node->left;
}
return node;
}
struct
Node* deleteNode(struct Node* root, int value)
{
if (root == NULL)
{
return root;
}
if (value < root->data)
{
root->left =
deleteNode(root->left, value);
}
else
if (value > root->data)
{
root->right =
deleteNode(root->right, value);
}
else
{
if (root->left == NULL)
{
struct Node* temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
struct Node* temp = root->left;
free(root);
return temp;
}
struct Node* temp =
findMin(root->right);
root->data = temp->data;
root->right =
deleteNode(root->right, temp->data);
}
return root;
}
void
main()
{
struct Node* root = NULL;
int choice, value;
while
(1)
{
printf("\nMenu:\n");
printf("1. Create BST\n");
printf("2. Display
(Inorder)\n");
printf("3. Delete
Element\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("Elements in BST
(Inorder): ");
inorder(root);
printf("\n");
break;
case 3:
printf("Enter element to
delete: ");
scanf("%d",
&value);
root = deleteNode(root, value);
printf("Element %d
deleted\n", value);
break;
case 4:
exit(0);
default:
printf("Invalid choice!
Select again.\n");
}
}
No comments:
Post a Comment