Skip to content

Instantly share code, notes, and snippets.

@ermiry
Created November 17, 2019 02:15
Show Gist options
  • Save ermiry/c5cf64cc1c1fc3d9a9fd314549d3ec49 to your computer and use it in GitHub Desktop.
Save ermiry/c5cf64cc1c1fc3d9a9fd314549d3ec49 to your computer and use it in GitHub Desktop.
AVL Tree Example
#include <stdlib.h>
#include <stdio.h>
#include "avl.h"
void avl_print (AVLNode *node) {
if (node) {
avl_print (node->right);
if (node->id) printf ("Username: %s\n", ((User *) node->id)->name);
avl_print (node->left);
}
}
int main (void) {
// create and initialize to default values our tree
AVLTree *tree = avl_init (user_comparator, user_delete);
User *erick = user_new ("erick", 1); // we create a new user
avl_insert_node (tree, erick); // insert the user into the tree
User *luis = user_new ("luis", 2); // we create a new user
avl_insert_node (tree, luis); // insert the user into the tree
User *isai = user_new ("isai", 3); // we create a new user
avl_insert_node (tree, isai); // insert the user into the tree
avl_print (tree->root);
// we can remove a node from the tree by passing a reference to its data
// and the tree will use the comparator method to do its magic and return
// the data ptr if it exists, if not, it will return NULL
User *luis_two = (User *) avl_remove_node (tree, luis);
user_delete (luis_two); // we msut delete this ptr
// we can use the comparator method and create a new user that we will use a query
// and get data from the tree
User *query = user_new ("erick", 2);
void *found_ptr = avl_get_node_data (tree, query);
if (found_ptr) {
User *found = (User *) found_ptr;
printf ("\nFound name: %s\n", found->name);
}
else printf ("\nNot found!!!\n");
user_delete (query); // the query must be deleted aftyer use
avl_print (tree->root);
// remember to delete the tree after use to avoid memory leaks
avl_delete (tree);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment