Example #1
0
void* rb_tree_insert(tree_root* root, void* node){
  tree_node *y = &RBNIL, *x = root->root;

  tree_node *z = new_rbtree_node(node);

  while(x != &RBNIL){
    y = x;

    if(root->compare(root->key(z), root->key(x)) == 0){
      void* holder = x->node;
      free(z);
      x->node = node;
      return holder;
    }

    if(root->compare(root->key(z), root->key(x)) < 0)
      x = x->left;
    else
      x = x->right;
  }

  z->parent = y;

  if(y == &RBNIL)
    root->root = z;
  else{
    if(root->compare(root->key(z),root->key(y)) < 0)
      y->left = z;
    else
      y->right = z;
  }

  rb_tree_insert_fixup(root, z);
  return NULL;
}
Example #2
0
void rb_tree_insert (RBTREE *T , NODE *x) {  
    NODE *temp = T->root;  
    NODE *log = T->nil;  

    if (temp == NULL) {  
        T->root = x;  
        x->left = T->nil;  
        x->right = T->nil;  
        x->parent = T->nil;  
    }else {  
        while (temp != T->nil) {  
            log = temp;  
            if (x->key > temp->key)  
                temp = temp->right;  
            else  
                temp = temp->left;  
        }
        if (log->key < x->key)  
            log->right = x;  
        else  
            log->left = x;  
        x->parent = log;  
    }  
    rb_tree_insert_fixup (T , x);  
}  
Example #3
0
bool rb_tree_insert(rb_tree_t *tree, void *key, bool *exists)
{
    rb_tree_node_t *x = NULL;
    rb_tree_node_t *y = NULL;
    rb_tree_node_t *z = NULL;

    *exists = false;

    /* First, search for the key. If it is present, all we need to do is to increase its count. */
    x = rb_tree_search_from(tree, tree->head, key);
    if (NULL != x) {
        *exists = true;
        x->count += 1;
        return true;
    }

    /* If the key doesn't exist, we need to allocate a new node for the key, and actually insert it */
    z = (rb_tree_node_t *) calloc(sizeof(rb_tree_node_t), 1);
    if (NULL == z) {
        return false;
    }
    z->key = key;
    z->count = 1;

    y = &(tree->nil);
    x = tree->head;

    while (!IS_NIL(tree, x)) {
        y = x;
        /* z->key < x->key */
        if (tree->key_cmp(z->key, x->key) < 0) {
            x = x->left;
        } else {
            x = x->right;
        }
    }

    z->parent = y;
    if (IS_NIL(tree, y)) {
        tree->head = z;
    } else {
        /* z->key < y->key */
        if (tree->key_cmp(z->key, y->key) < 0) {
            y->left = z;
        } else {
            y->right = z;
        }
    }
    z->left = &(tree->nil);
    z->right = &(tree->nil);
    z->color = RED;
    rb_tree_insert_fixup(tree, z);

    /* In this case, a unique key is add to the tree */
    tree->count++;
    tree->max = rb_tree_find_max(tree);

    return true;
}