Write a Modular C Programming code for Binary Search Tree (Insertion, Searching, Display) Multiple Data DSA
What is Binary Search Tree?
Binary Search Tree is a node-based binary tree data structure which has the following properties:
- The left subtree of a node contains only nodes with keys lesser than the node’s key.
- The right subtree of a node contains only nodes with keys greater than the node’s key.
- The left and right subtree each must also be a binary search tree.
CODE:
#include<stdio.h> struct student{ char name[20]; int roll; int marks; }; struct student hi; struct node { struct student s; struct node *left, *right; }; struct node* root = NULL; struct node* newNode(struct student* ii) { struct node* temp; temp= (struct node*)malloc(sizeof(struct node)); temp->s = *ii; temp->left = temp->right = NULL; return temp; } void print(struct node* root) { if (root != NULL) { print(root->left); printf("\nName: %s",root->s.name); printf("\tRoll: %d",root->s.roll); printf("\tmarks: %d\n",root->s.marks); print(root->right); } return; } int search(struct node* node, int key) { if (node->s.roll == key) return 1; if (key < node->s.roll){ node->left = search(node->left, key); return 1;} else if (key > node->s.roll){ node->right = search(node->right, key); return 1;} return 0; } struct node* insert(struct node* node, struct student* s) { if (node == NULL) return newNode(s); if (s->roll < node->s.roll) node->left = insert(node->left, s); else if (s->roll > node->s.roll) node->right = insert(node->right, s); return node; } int main() { int data,no; printf("Enter the no. of Students: "); scanf("%d",&no); for(int i=0;i<no;i++){ printf("\nEnter Name: "); scanf("%s",hi.name); printf("Enter Roll No: "); scanf("%d",&hi.roll); printf("Enter Marks: "); scanf("%d",&hi.marks); root = insert(root, &hi); } print(root); printf("\nEnter Roll No To search: "); scanf("%d",&data); if(search(root,data)){ printf("\nFOUND!!!\n"); exit(0);} else{ printf("\nNOT FOUND!!!\n"); exit(0);} }
OUTPUT
Enter the no. of Students: 3 Enter Name: AAA Enter Roll No: 123 Enter Marks: 320 Enter Name: BBB Enter Roll No: 222 Enter Marks: 363 Enter Name: CCC Enter Roll No: 333 Enter Marks: 965 Name: AAA Roll: 123 marks: 320 Name: BBB Roll: 222 marks: 363 Name: CCC Roll: 333 marks: 965 Enter Roll No To search: 333 FOUND!!! Process returned 0 (0x0) execution time : 40.781 s Press any key to continue.
Please find some more codes of Loops, Condition Statements, 1D Arrays, 2D Arrays, Strings, Pointers, Data Structures, Files, Linked lists, Stacks, Queues, Binary Trees, MISC, Solved model question papers & Hacker Rank all solutions on the below page:
Top 100+ C Programming codes – KLE Technological University