From c36c7fedf969fa49e832c7d2739ea4d1ad1108f2 Mon Sep 17 00:00:00 2001 From: Jonas Gunz Date: Mon, 16 Mar 2020 16:59:36 +0100 Subject: updated tree to be generic --- src/tree.c | 24 +++++++++++++++++++++--- src/tree.h | 10 +++++++++- 2 files changed, 30 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/tree.c b/src/tree.c index c6fc33b..899514e 100644 --- a/src/tree.c +++ b/src/tree.c @@ -37,9 +37,27 @@ int tree_balance ( struct tree_node** _root ) return 1; } -int tree_destroy ( struct tree_node** _root ) +int tree_destroy ( struct tree_node** _root, uint8_t _options ) { - return 1; + while(*_root) + { + struct tree_node** node = _root; + + while( (*node)->above || (*node)->below ) + node= (*node)->above ? & (*node)->above : & (*node)->below ; + + printf( "%s\n", (*node)->data ); + + if (_options & _TREE_FREE_KEY) + free( (*node)->data ); + if (_options & _TREE_FREE_KEY) + free( (*node)->key ); + + free ( *node ); + *node = NULL; + } + + return 0; } int string_compare ( char* _1, char* _2 ) @@ -88,7 +106,7 @@ void* tree_get ( struct tree_node** _root, char* _query ) } } - return *node ? (*node)->key : NULL; + return *node ? (*node)->data : NULL; return 0; } diff --git a/src/tree.h b/src/tree.h index 958b5ed..38b4b38 100644 --- a/src/tree.h +++ b/src/tree.h @@ -9,6 +9,11 @@ #include #include +#include + +#define _TREE_FREE_DATA 0x01 +#define _TREE_FREE_KEY 0x02 + struct tree_node { char* key; void* data; @@ -20,9 +25,12 @@ int tree_insert ( struct tree_node** _root, char* _key, void* _data ); int tree_balance( struct tree_node** _root ); +/** + * Returns (void*)node->data on success, NULL on failure + * */ void* tree_get ( struct tree_node** _root, char* _query ); -int tree_destroy( struct tree_node** _root ); +int tree_destroy( struct tree_node** _root, uint8_t _options ); /** * ignore-case alphabetical string compare -- cgit v1.2.3