//Main insertion function node * insert( node * root, int key, int value ) { record * pointer; node * leaf; /* The current implementation ignores * duplicates. */ if (find(root, key, false) != NULL) return root; /* Create a new record for the * value. */ pointer = make_record(value); /* Case: the tree does not exist yet. * Start a new tree. */ if (root == NULL) return start_new_tree(key, pointer); /* Case: the tree already exists. * (Rest of function body.) */ leaf = find_leaf(root, key, false); /* Case: leaf has room for key and pointer. */ if (leaf->num_keys < order - 1) { leaf = insert_into_leaf(leaf, key, pointer); return root; } /* Case: leaf must be split. */ return insert_into_leaf_after_splitting(root, leaf, key, pointer); }
node *insert(node *root, char *key, void *data) { node *leaf; int index, cond; leaf = find_leaf(root, key); if (!leaf){ // cannot find the leaf, the tree is empty return make_new_tree(key, data); } for (index = 0; index < leaf->num_keys && (cond = strcmp(leaf->keys[index], key)) < 0; index++) ; if (cond == 0) // ignore duplicates return root; if (leaf->num_keys < size - 1){ insert_into_leaf(leaf, index, key, data); return root; // the root remains unchanged } return insert_into_leaf_after_splitting(root, leaf, index, key, data); }
/** * Master insertion function. * Inserts a key and an associated value into * the B+ tree, causing the tree to be adjusted * however necessary to maintain the B+ tree * properties. * * @param root the root nodes * @param key the key to be used to identify the object * @param value the pointer to the object * @return the new root node */ BtreeNode_t * BtreeInsert(BtreeNode_t * root, void *key, void *value, int (*keyCMP)(void *key1, void *key2)) { BtreeRecord_t * pointer; BtreeNode_t * leaf; /* The current implementation ignores * duplicates. */ if ((pointer = BTreeFind(root, key, keyCMP)) != NULL) { return root; } /* Create a new record for the * value. */ pointer = make_record(value); /* Case: the tree does not exist yet. * Start a new tree. */ if (root == NULL) return start_new_tree(key, pointer); /* Case: the tree already exists. * (Rest of function body.) */ leaf = find_leaf(root, key, keyCMP); /* Case: leaf has room for key and pointer. */ if (leaf->num_keys < order - 1) { leaf = insert_into_leaf(leaf, key, pointer, keyCMP); return root; } /* Case: leaf must be split. */ return insert_into_leaf_after_splitting(root, leaf, key, pointer, keyCMP); }
node * insert(node *root, int key, int value) { record* pointer; node* leaf; pointer = make_record(value); if (root == NULL) return start_new_tree(key, pointer); leaf = find_leaf(root, key); if (leaf->num_keys < order - 1) { leaf = insert_into_leaf(leaf, key, pointer); return root; } return insert_into_leaf_after_splitting(root, leaf, key, pointer); }