bst.c (2123B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <stdbool.h> 4 5 struct node{ 6 struct node* left; 7 struct node* right; 8 int data; 9 } *root; 10 11 bool isNULL(struct node* r){ 12 if(r == NULL) 13 return true; 14 return false; 15 } 16 17 void createRoot(int data) { 18 root = (struct node*)malloc(sizeof(struct node)); 19 if(isNULL(root)){ 20 printf("Insufficient memory.\n"); 21 return; 22 } 23 root->data = data; 24 root->left = root->right = NULL; 25 } 26 27 struct node* getnode(int data){ 28 struct node* temp = (struct node *)malloc(sizeof(struct node)); 29 if(isNULL(temp)) 30 printf("Insufficient memory.\n"); 31 else{ 32 temp->left = temp->right = NULL; 33 temp->data = data; 34 } 35 return temp; 36 } 37 38 void insert(int data, struct node* parent){ 39 if(data < parent->data) 40 if(!isNULL(parent->left)) 41 insert(data, parent->left); 42 else parent->left = getnode(data); 43 else 44 if(!isNULL(parent->right)) 45 insert(data, parent->right); 46 else parent->right = getnode(data); 47 } 48 49 bool contains(int data, struct node *parent){ 50 if(isNULL(parent)) 51 return false; 52 if(parent->data == data) 53 return true; 54 if(data < parent->data) 55 return contains(data, parent->left); 56 if(data > parent->data) 57 return contains(data, parent->right); 58 } 59 60 void printInOrder(struct node* parent){ 61 if(!isNULL(parent->left)) 62 printInOrder(parent->left); 63 printf("%d ", parent->data); 64 if(!isNULL(parent->right)) 65 printInOrder(parent->right); 66 } 67 68 int main(){ 69 int choice, d; 70 do{ 71 printf("Your choice> "); 72 scanf("%d", &choice); 73 switch (choice) { 74 case 1: 75 printf("Enter a number: "); 76 scanf("%d", &d); 77 if(isNULL(root)) createRoot(d); 78 else insert(d, root); 79 break; 80 case 2: 81 printf("Enter the element to be searched: "); 82 scanf("%d", &d); 83 printf("%d\n", contains(d, root)); 84 break; 85 case 3: 86 if(isNULL(root)) printf("Empty tree.\n"); 87 else printInOrder(root); 88 break; 89 case 4: 90 choice = 0; 91 } 92 }while(choice); 93 return 0; 94 }