user3224237 user3224237 - 1 year ago 49
C Question

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

The only way I see to access all nodes (if the keys are not known) is

. Is it allowed to use
? If not--how delete all nodes? (I don't wan't to use the non-portable GNU extension

Answer Source

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);