Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Github: https://github.com/nezvers
- Youtube: https://www.youtube.com/channel/UCb4-Y0E6mmwjtawcitIAzKQ
- Twitter: https://twitter.com/NeZversStudio
- */
- #include <stdio.h>
- #include <stdlib.h>
- // BINARY SEARCH TREE
- typedef struct Node{
- int value;
- struct Node *left;
- struct Node *right;
- }Node;
- Node* newNode(int value){
- Node *n = (Node*)malloc(sizeof(Node));
- n->value = value;
- n->left = NULL;
- n->right = NULL;
- return n;
- }
- void insert_value(Node **node, int value){
- if(!(*node)){
- Node *temp = NULL;
- temp = (Node *)malloc(sizeof(Node));
- temp->left = temp->right = NULL;
- temp->value = value;
- *node = temp;
- //printf("insert new: %d\n", (*node)->value);
- return;
- }
- else if(value < (*node)->value){
- //printf("insert left: %d < %d\n", value, (*node)->value);
- insert_value(&(*node)->left, value);
- }
- else if(value > (*node)->value){
- //printf("insert right: %d > %d\n", value, (*node)->value);
- insert_value(&(*node)->right, value);
- }
- }
- Node* search_tree(Node **node, int value){
- if(!(*node)){
- //printf("search NULL\n");
- return NULL;
- }
- else if(value == (*node)->value){
- //printf("search found: %d > %d\n", value, (*node)->value);
- return *node;
- }
- else if(value < (*node)->value){
- //printf("search left: %d > %d\n", value, (*node)->value);
- return search_tree(&((*node)->left), value);
- }
- else if(value > (*node)->value){
- //printf("search right: %d > %d\n", value, (*node)->value);
- return search_tree(&((*node)->right), value);
- }
- //printf("search error: %d\n", value);
- return NULL;
- }
- Node* create_tree(int data[], int size){
- Node *root = NULL;
- for(int i=0; i<size; i++){
- insert_value(&root, data[i]);
- //printf("inserted \n");
- }
- return root;
- }
- void destroy_tree(Node *node){
- destroy_tree(node->left);
- destroy_tree(node->right);
- free(node);
- }
- int main(){
- int data[] = {6,5,7,3,4,9,8,2,1};
- Node *root = create_tree(data, sizeof(data)/sizeof(data[0]));
- printf("\n");
- Node *node = search_tree(&root, 8);
- printf("found value: %d\n", node->value);
- return 0;
- }
Add Comment
Please, Sign In to add comment