|
|
|
@ -28,6 +28,9 @@ TR_treeInsert(TR_Tree * this, const void * search, TR_TreeComp comp) |
|
|
|
{ |
|
|
|
TR_Tree node = *this; |
|
|
|
TR_Tree new_node = NULL; |
|
|
|
int found; |
|
|
|
|
|
|
|
TR_TREE_FIND(node, search, found, comp); |
|
|
|
|
|
|
|
/* |
|
|
|
* insert the node or return the one in tree if comparison |
|
|
|
@ -40,43 +43,24 @@ TR_treeInsert(TR_Tree * this, const void * search, TR_TreeComp comp) |
|
|
|
*/ |
|
|
|
*this = node = new_node = TR_new(TR_Tree, search); |
|
|
|
} else { |
|
|
|
/* |
|
|
|
* first search for it and if its found return the data |
|
|
|
* and we are done... |
|
|
|
*/ |
|
|
|
while (NULL != node) { |
|
|
|
int comparison = comp(node->data, search); |
|
|
|
|
|
|
|
if (0 < comparison) { |
|
|
|
if (NULL != TR_TREE_LEFT(node)) { |
|
|
|
node = TR_TREE_LEFT(node); |
|
|
|
continue; |
|
|
|
} else { |
|
|
|
node->left = TR_new(TR_Tree, search); |
|
|
|
node->left->parent = node; |
|
|
|
node = new_node = node->left; |
|
|
|
break; |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
if (0 > comparison) { |
|
|
|
if (NULL != TR_TREE_RIGHT(node)) { |
|
|
|
node = TR_TREE_RIGHT(node); |
|
|
|
continue; |
|
|
|
} else { |
|
|
|
node->right = TR_new(TR_Tree, search); |
|
|
|
node->right->parent = node; |
|
|
|
node = new_node = node->right; |
|
|
|
break; |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
if (0 == comparison) { |
|
|
|
// as this is insert and not find this will overwrite an existing value, |
|
|
|
// but return the previos one so that it can be freed if neccessary. |
|
|
|
void * data = node->data; |
|
|
|
node->data = (void *)search; |
|
|
|
return data; |
|
|
|
if (found == 0) { |
|
|
|
// we found an element |
|
|
|
// as this is insert and not find this will overwrite an existing |
|
|
|
// value, but return the previous one so that it can be freed if |
|
|
|
// neccessary. |
|
|
|
void * data = node->data; |
|
|
|
node->data = (void *)search; |
|
|
|
return data; |
|
|
|
} else { |
|
|
|
// not found |
|
|
|
if (0 < found) { |
|
|
|
node->left = TR_new(TR_Tree, search); |
|
|
|
node->left->parent = node; |
|
|
|
node = new_node = node->left; |
|
|
|
} else { |
|
|
|
node->right = TR_new(TR_Tree, search); |
|
|
|
node->right->parent = node; |
|
|
|
node = new_node = node->right; |
|
|
|
} |
|
|
|
} |
|
|
|
} |
|
|
|
@ -114,13 +98,13 @@ TR_treeInsert(TR_Tree * this, const void * search, TR_TreeComp comp) |
|
|
|
&& node->parent == node->parent->parent->left) { |
|
|
|
|
|
|
|
TR_TREE_ROTATE(left, this, node->parent); |
|
|
|
node = TR_TREE_LEFT(node); |
|
|
|
node = node->left; |
|
|
|
|
|
|
|
} else if (node == node->parent->left |
|
|
|
&& node->parent == node->parent->parent->right) { |
|
|
|
|
|
|
|
TR_TREE_ROTATE(right, this, node->parent); |
|
|
|
node = TR_TREE_RIGHT(node); |
|
|
|
node = node->right; |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
|