Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all nodes from a POSIX binary (tsearch) tree?

Tags:

c

binary-tree

The only way I see to access all nodes (if the keys are not known) is twalk. Is it allowed to use tdelete inside twalk? If not--how delete all nodes? (I don't wan't to use the non-portable GNU extension tdestroy.)

like image 891
user3224237 Avatar asked Sep 19 '16 09:09

user3224237


1 Answers

No, you don't need to use twalk, you can use tdelete with a comparison function (the same function used to insert), tdelete changes the root node, so passing and deleting while (root != NULL) will do the trick, something like:

typedef struct {
    int key;
    char value[50];
} t_data;

static int comp(const void *pa, const void *pb)
{
    const t_data *a = pa, *b = pb;

    if (a->key > b->key) return +1;
    if (a->key < b->key) return -1;
    return 0;
}

int main(void)
{
    void *root = NULL;
    t_data *data;    

    ...

    while (root != NULL) {
        data = *(t_data **)root;
        tdelete(data, &root, comp);
        free(data);
    }

    ...
like image 116
David Ranieri Avatar answered Nov 15 '22 02:11

David Ranieri