c - Red Black Tree - Initialization -
how can correctly initialize red black tree in c?
structure:
typedef struct node{ int key; struct node *left; struct node *right; struct node *parent; enum {red, black} color; }node; typedef struct rbtree{ struct node *root; struct node *nil; }rbtree;
main function:
int main(){ rbtree *tree; init_rbtree(&tree); }
init function:
void init_rbtree(rbtree **t){ (*t)->root = null; node *n = (node*)malloc(sizeof(node)); if(n != null){ n->color = black; (*t)->nil = n; } }
the program crashes run code.
you need allocate memory *t
before can use it.
void init_rbtree(rbtree **t) { *t=malloc(sizeof(rbtree)); if (*t==null) { //handle error } else { (*t)->root = null; node *n = malloc(sizeof(node)); if(n != null){ n->color = black; (*t)->nil = n; } } }
Comments
Post a Comment