Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- typedef struct tree_t
- {
- int num;
- struct tree_t *left;
- struct tree_t *right;
- } tree;
- tree* search_get_node(int num, tree **head)
- {
- tree *curr = *head;
- if(num < curr->num)
- {
- if(curr->left == NULL)
- {
- return curr;
- }
- curr = curr->left;
- return search_get_node(num, &curr);
- }
- if(num > curr->num)
- {
- if(curr->right == NULL)
- {
- return curr;
- }
- curr = curr->right;
- return search_get_node(num, &curr);
- }
- if(num == curr->num)
- {
- return curr;
- }
- }
- void add_node(tree *n, tree **head)
- {
- tree *curr = search_get_node(n->num, head);
- if(n->num < curr->num)
- {
- if(curr->left == NULL)
- {
- curr->left = n;
- return;
- }
- }
- if(n->num > curr->num)
- {
- if(curr->right == NULL)
- {
- curr->right = n;
- return;
- }
- }
- /* If equal, then free & ignore since its already in the tree */
- free(n);
- }
- void add(int num, tree **head)
- {
- tree *n = (tree*) malloc(sizeof(tree));
- n->num = num;
- n->left = NULL;
- n->right = NULL;
- add_node(n, head);
- }
- int search(int num, tree **head)
- {
- tree* t = search_get_node(num, head);
- return num == t->num;
- }
- void free_tree(tree* head)
- {
- if(head == NULL)
- {
- return;
- }
- free_tree(head->left);
- free_tree(head->right);
- free(head);
- }
- int main(int argc, char** argv)
- {
- srand(time(NULL));
- tree *head = (tree*) malloc(sizeof(tree));
- head->num = rand() + 1;
- head->left = NULL;
- head->right = NULL;
- int i;
- for(i = 1; i < 9999999; i++)
- {
- unsigned int n = (rand()) + 1;
- add(n, &head);
- }
- free_tree(head);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement