#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 = newNode->right =
NULL;
return newNode;
}
struct
Node* insert(struct Node* root, int value)
{
if (!root)
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)
return;
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
struct
Node* search(struct Node* root, int value)
{
if (!root || root->data == value)
return
root;
return (value
< root->data) ? search(root->left, value) : search(root->right,
value);
}
void
main()
{
struct Node* root = NULL;
int choice, value, s_value;
struct Node* f_value;
while(1)
{
printf("\nMenu:\n1. Create BST\n2.
Display (Inorder)\n3. Search Element\n4. Exit\nEnter 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
search: ");
scanf("%d", &s_value);
f_value = search(root, s_value);
printf("Element %d %s in
BST.\n", s_value, f_value ? "found" : "not found");
break;
case 4:
exit(0);
default:
printf("Invalid choice!
Select again.\n");
}
}
}
x
No comments:
Post a Comment