0% found this document useful (0 votes)
5 views2 pages

BST LL PGM

The document contains a C program that implements a binary search tree with functionalities to insert nodes, perform inorder traversal, and search for a specific key. It defines a structure for tree nodes and provides functions for creating new nodes, inserting data, traversing the tree, and searching for keys. The main function presents a menu-driven interface for user interaction with the tree operations.

Uploaded by

chinnenavya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

BST LL PGM

The document contains a C program that implements a binary search tree with functionalities to insert nodes, perform inorder traversal, and search for a specific key. It defines a structure for tree nodes and provides functions for creating new nodes, inserting data, traversing the tree, and searching for keys. The main function presents a menu-driven interface for user interaction with the tree operations.

Uploaded by

chinnenavya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <stdlib.h>
struct Node {
int data;
struct Node *left, *right;
};
struct Node* newNode(int item) {
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}
struct Node* insert(struct Node* node, int data) {
if (node == NULL)
return newNode(data);
if (data < node->data)
node->left = insert(node->left, data);
else if (data > node->data)
node->right = insert(node->right, data);
return node;
}
void inorder(struct Node* root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}

struct Node* search(struct Node* root, int key) {


if (root == NULL || root->data == key)
return root;
if (key < root->data)
return search(root->left, key);
else
return search(root->right, key);
}

int main() {
struct Node* root = NULL;
int choice, data, key;
while (1) {
printf("\nMenu:\n");
printf("1. Insert\n");
printf("2. Inorder Traversal\n");
printf("3. Search\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter data to insert: ");
scanf("%d", &data);
root = insert(root, data);
break;
case 2:
printf("Inorder traversal: ");
inorder(root);
printf("\n");
break;
case 3:
printf("Enter key to search: ");
scanf("%d", &key);
struct Node* result = search(root, key);
if (result != NULL)
printf("Key %d found.\n", key);
else
printf("Key %d not found.\n", key);
break;
case 4:
exit(0);
default:
printf("Invalid choice.\n");
}
}

return 0;
}

You might also like