nezvers

Binary search tree

Jan 29th, 2021 (edited)
662
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.06 KB | None | 0 0
  1. /*
  2. Github: https://github.com/nezvers
  3. Youtube: https://www.youtube.com/channel/UCb4-Y0E6mmwjtawcitIAzKQ
  4. Twitter: https://twitter.com/NeZversStudio
  5. */
  6.  
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9.  
  10. // BINARY SEARCH TREE
  11.  
  12. typedef struct Node{
  13.     int value;
  14.     struct Node *left;
  15.     struct Node *right;
  16. }Node;
  17.  
  18. Node* newNode(int value){
  19.     Node *n = (Node*)malloc(sizeof(Node));
  20.     n->value = value;
  21.     n->left = NULL;
  22.     n->right = NULL;
  23.     return n;
  24. }
  25.  
  26. void insert_value(Node **node, int value){
  27.     if(!(*node)){
  28.         Node *temp = NULL;
  29.         temp = (Node *)malloc(sizeof(Node));
  30.         temp->left = temp->right = NULL;
  31.         temp->value = value;
  32.         *node = temp;
  33.         //printf("insert new: %d\n", (*node)->value);
  34.         return;
  35.     }
  36.     else if(value < (*node)->value){
  37.         //printf("insert left: %d < %d\n", value, (*node)->value);
  38.         insert_value(&(*node)->left, value);
  39.     }
  40.     else if(value > (*node)->value){
  41.         //printf("insert right: %d > %d\n", value, (*node)->value);
  42.         insert_value(&(*node)->right, value);
  43.     }
  44. }
  45.  
  46. Node* search_tree(Node **node, int value){
  47.     if(!(*node)){
  48.         //printf("search NULL\n");
  49.         return NULL;
  50.     }
  51.     else if(value == (*node)->value){
  52.         //printf("search found: %d > %d\n", value, (*node)->value);
  53.         return *node;
  54.     }
  55.     else if(value < (*node)->value){
  56.         //printf("search left: %d > %d\n", value, (*node)->value);
  57.         return search_tree(&((*node)->left), value);
  58.     }
  59.     else if(value > (*node)->value){
  60.         //printf("search right: %d > %d\n", value, (*node)->value);
  61.         return search_tree(&((*node)->right), value);
  62.     }
  63.     //printf("search error: %d\n", value);
  64.     return NULL;
  65. }
  66.  
  67. Node* create_tree(int data[], int size){
  68.     Node *root = NULL;
  69.     for(int i=0; i<size; i++){
  70.         insert_value(&root, data[i]);
  71.         //printf("inserted \n");
  72.     }
  73.     return root;
  74. }
  75.  
  76. void destroy_tree(Node *node){
  77.     destroy_tree(node->left);
  78.     destroy_tree(node->right);
  79.     free(node);
  80. }
  81.  
  82. int main(){
  83.     int data[] = {6,5,7,3,4,9,8,2,1};
  84.     Node *root = create_tree(data, sizeof(data)/sizeof(data[0]));
  85.     printf("\n");
  86.     Node *node = search_tree(&root, 8);
  87.     printf("found value: %d\n", node->value);
  88.     return 0;
  89. }
Add Comment
Please, Sign In to add comment