예제 #1
0
treeNode *insert(treeNode *node, KEY *key, VALUE *value) {
	if (node == NULL) {
		treeNode *temp;
		temp = malloc(sizeof(treeNode));
		temp->key = key;
		temp->value = value;
		temp->left = NULL;
		temp->right = NULL;
		return temp;
	}

	if (compare((void *) key, (void *) node->key) > 0) {
		node->right = insert(node->right, key, value);
		node = reBalance(node);
	} else if (compare((void *) key, (void *) node->key) < 0) {
		node->left = insert(node->left, key, value);
		node = reBalance(node);
	}

	/* if reached here then value of a label/variable has changed */
	else {
		node->value = value;
	}
	return node;
}
예제 #2
0
파일: tmap.c 프로젝트: wfei/hw
NODE * tmap_insertR(TMAP *t, NODE *r, NODE *parent, char * name, double val, char side, char parentBalance, int depth){
    //-------------    
    //need to check whether is size-balanced each time insert
    char balanced;
    balanced = Balance(r, name, val);
    //------------

    NODE *leaf;
    depth++;
    if(r == NULL){
	leaf = (NODE *)malloc(sizeof(NODE));
	leaf->left = NULL;
	leaf->right = NULL;
	leaf->nameVal.name = name;
	leaf->nameVal.value = val;
	(*t)->size++;
	if (depth > (*t)->height) {
	    (*t)->height = depth;
	}
	((*t)->numOfInsertion)++; 
	tableInsert((*t)->hashTable, name, leaf, h_One);
	return leaf;
    }

    // the tie is broken by the name
    // (by standard alphabetical order)
    if(r->nameVal.value == val){
	if(strcmp(r->nameVal.name, name) > 0){
	    r->left = tmap_insertR(t, r->left, r, name, val, 0, balanced, depth);
	}else{
	    r->right = tmap_insertR(t, r->right, r, name, val, 1, balanced, depth);
	}
    } else if(val < r->nameVal.value){
	r->left = tmap_insertR(t, r->left, r, name, val, 0, balanced, depth);
    } else {
	r->right = tmap_insertR(t, r->right, r, name, val, 1, balanced, depth);
    }
    
    // if the nearest node is not found and the sub-tree is not balanced
    if (parentBalance == BALANCED && balanced == INBALANCED) {
	((*t)->numOfRebalance)++;
	if (parent != NULL) { // if non-root subtree is balanced
	    if (side == 0) {
		parent->left = reBalance(r);
		(*t)->height = calHeight((*t)->root);
		return parent->left;
	    } else if (side == 1) {
		parent->right = reBalance(r);
		(*t)->height = calHeight((*t)->root);
		return parent->right;
	    }
	} else {
	    (*t)->root = reBalance(r);
	    (*t)->height = calHeight((*t)->root);
	    return (*t)->root;
	}
	
    } else {
	return r;
    }
}// end of tmap_insertR