-
-
Save Sanusihassan/f968b1d6d16af80f97661459d14fed7a to your computer and use it in GitHub Desktop.
Binary Tree implementation in c
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
typedef struct tree | |
{ | |
int data; | |
struct tree *left; | |
struct tree *right; | |
} tree_node; | |
tree_node *create(int data, tree_node *left, tree_node *right) | |
{ | |
tree_node *node = malloc(sizeof(tree_node)); | |
node->data = data; | |
node->left = left; | |
node->right = right; | |
return node; | |
} | |
void print(tree_node *root) | |
{ | |
if (root == NULL) | |
{ | |
return; | |
} | |
printf("%d ", root->data); | |
print(root->left); | |
print(root->right); | |
} | |
void add(tree_node **root, int data) | |
{ | |
tree_node *new_node = create(data, NULL, NULL); | |
if (!(*root)) | |
{ | |
(*root) = new_node; | |
return; | |
} | |
else if (data <= (*root)->data) | |
{ | |
add(&(*root)->left, data); | |
} | |
else | |
{ | |
add(&(*root)->right, data); | |
} | |
} | |
_Bool search(tree_node *root, int data) | |
{ | |
_Bool retval; | |
if (root == NULL) | |
{ | |
return 0; | |
} | |
if (root->data == data) | |
{ | |
return 1; | |
} | |
else | |
{ | |
if (root->data >= data) | |
{ | |
retval = search(root->left, data); | |
} | |
else | |
{ | |
retval = search(root->right, data); | |
} | |
} | |
return retval; | |
} | |
tree_node *min(tree_node *root) | |
{ | |
if (!root) | |
{ | |
printf("Tree is empty"); | |
exit(1); | |
} | |
tree_node *ret_val; | |
if (root->left == NULL) | |
{ | |
ret_val = root; | |
} | |
else | |
{ | |
ret_val = min(root->left); | |
} | |
return ret_val; | |
} | |
tree_node *max(tree_node *root) | |
{ | |
if (!root) | |
{ | |
printf("Tree is empty"); | |
exit(1); | |
} | |
tree_node *ret_val; | |
if (root->right == NULL) | |
{ | |
ret_val = root; | |
} | |
else | |
{ | |
ret_val = max(root->right); | |
} | |
return ret_val; | |
} | |
void main() | |
{ | |
tree_node *root = NULL; | |
add(&root, 15); | |
add(&root, 10); | |
add(&root, 20); | |
add(&root, 25); | |
add(&root, 8); | |
add(&root, 12); | |
add(&root, 50); | |
tree_node *min_el = min(root); | |
tree_node *max_el = max(root); | |
// print(root); | |
printf("%d %d", min_el->data, max_el->data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment