Example #1
0
/* *
 * rb_tree_create - creates a new red-black tree, the 'compare' function
 * is required and returns 'NULL' if failed.
 *
 * Note that, root->left should always point to the node that is the root
 * of the tree. And nil points to a 'NULL' node which should always be
 * black and may have arbitrary children and parent node.
 * */
rb_tree *
rb_tree_create(int (*compare)(rb_node *node1, rb_node *node2)) {
    assert(compare != NULL);

    rb_tree *tree;
    rb_node *nil, *root;

    if ((tree = kmalloc(sizeof(rb_tree))) == NULL) {
        goto bad_tree;
    }

    tree->compare = compare;

    if ((nil = rb_node_create()) == NULL) {
        goto bad_node_cleanup_tree;
    }

    nil->parent = nil->left = nil->right = nil;
    nil->red = 0;
    tree->nil = nil;

    if ((root = rb_node_create()) == NULL) {
        goto bad_node_cleanup_nil;
    }

    root->parent = root->left = root->right = nil;
    root->red = 0;
    tree->root = root;
    return tree;

bad_node_cleanup_nil:
    kfree(nil);
bad_node_cleanup_tree:
    kfree(tree);
bad_tree:
    return NULL;
}
Example #2
0
// Creates (malloc'ates) 
int
rb_tree_insert (struct rb_tree *self, void *value) {
    return rb_tree_insert_node(self, rb_node_create(value));
}