ADVANCED CODING ASSIGNMENT -2
K CHANDRASEKHAR
VU21CSEN0100404
2. Write a program to implement binary search tree using
linked list.
#CODE:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct Node* insert(struct Node* root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insert(root->left, data);
} else if (data > root->data) {
root->right = insert(root->right, data);
}
return root;
}
struct Node* search(struct Node* root, int key) {
if (root == NULL || root->data == key) {
return root;
}
if (key > root->data) {
return search(root->right, key);
}
return search(root->left, key);
}
void inorder(struct Node* root) {
if (root != NULL) {
inorder(root->left);
printf("%d -> ", root->data);
inorder(root->right);
}
}
void freeTree(struct Node* root) {
if (root == NULL) {
return;
}
freeTree(root->left);
freeTree(root->right);
free(root);
}
int main() {
struct Node* root = NULL;
int choice, value, key;
while (1) {
printf("\n1. Insert a node\n2. Search a node\n3. Display inorder\n4. 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);
printf("Node inserted.\n");
break;
case 2:
printf("Enter value to search: ");
scanf("%d", &key);
if (search(root, key)) {
printf("Node found.\n");
} else {
printf("Node not found.\n");
}
break;
case 3:
printf("Inorder traversal of the binary search tree: ");
inorder(root);
printf("NULL\n");
break;
case 4:
freeTree(root);
printf("Exiting...\n");
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}
OUTPUT: