Example #1
0
File: bst.c Project: dxtr/bst
/* Creates a new node and inserts it in the tree specified by root
 * Arguments: the tree, a comparison function and the data the node will contain
 * If NULL is passed instead of the comparison function it will blindly insert
 * the data (Not taking duplicates into consideration, etc)
 */
bst_node* bst_insert(bst_node* root, uint64_t key, int (*compare)(list_node*,void*), void *data)
{
	if (root == NULL || data == NULL) return NULL; // We return NULL because we won't insert any data anyway

	bst_node** node = bst_search(&root, key);
	if (*node == NULL) {
		*node = bst_new_node(key, data);
	} else if (list_find((*node)->list, compare, data) == NULL) {
		list_insert((*node)->list, data);
	}

	return *node;
}
Example #2
0
bst_node_t *bst_insert_node(bst_node_t *node, char *key, stable_data_t *data)
{
    if(node == NULL) {
        return bst_new_node(key, data);
    } else {
        // Don't allow duplicates
        int sres = strcmp(key, node->key);
        if(sres < 0)
            node->left = bst_insert_node(node->left, key, data);
        else if(sres > 0)
            node->right = bst_insert_node(node->right, key, data);
    }

    return node;
}
Example #3
0
int main(int argc, char *argv[])
{
    char *ta[] = { "key", "Key", "string", "sTrIng", "STRING", "id",
                   "num", "i", "I", "key", "asdf3", "tea23", "_2314", NULL };
    int rc = 0;
    bst_node_t *root = NULL;
    stable_data_t data = { .type = LEX_EOF, .var.val.i = 1 };
    // Test alloc
    root = bst_new_node("j", &data);

    // Test insert
    for(unsigned int i = 0; ta[i] != NULL; i++)
        root = bst_insert_node(root, ta[i], &data);

    // Print tree
    debug_bst_print_tree(root);
    printf("Size: %d\n", debug_bst_size(root));

    // Test lookup
    for(unsigned int i = 0; ta[i] != NULL; i++) {
        bst_node_t *search = bst_lookup_node(root, ta[i]);
        if(search == NULL) {
            fprintf(stderr, "[FAIL] Couldn't find node with value %s\n", ta[i]);
            rc = 1;
        } else {
            if(strcmp(ta[i], search->key) == 0) {
                fprintf(stderr, "[PASS] Found node with correct value (%s == %s) (%d)\n",
                        ta[i], search->key, search->data.var.val.i);
            } else {
                fprintf(stderr, "[FAIL] Found node with incorrect value (%s != %s)\n",
                        ta[i], search->key);
                rc = 1;
            }
        }
    }

    // Test free (check with valgrind)
    bst_destroy(root);

    return rc;
}
Example #4
0
int bst_insert(bstree**t, bskey key)
{
    bstree *p = NULL;
    bstree *s = NULL;

    if (t != NULL && bst_search(*t, key, NULL, &p) > 0) {
        return 0;
    }

    s = bst_new_node(key);
    if (s == NULL)
        return 0;

    if (!p)
        *t=s;
    else if (key < p->key)
        p->l=s;
    else if (key > p->key)
        p->r=s;

    return 1; 
}