diff --git a/src/BinaryTree/BinaryTree.c b/src/BinaryTree/BinaryTree.c index e31c79d..725d81a 100644 --- a/src/BinaryTree/BinaryTree.c +++ b/src/BinaryTree/BinaryTree.c @@ -150,18 +150,18 @@ static int _BinaryTree_DestroyNode(BinaryTree* tree, BinaryTreeNode* node) return EXIT_SUCCESS; } -static BinaryTreeNode** _BinaryTreeNode_SmallestNodeLocation(BinaryTreeNode* node) +static BinaryTreeNode* _BinaryTreeNode_SmallestNodeParent(BinaryTreeNode* node) { if (node->left == NULL) { return NULL; } - BinaryTreeNode** smallest_location = &node->left; - do { - smallest_location = &(*smallest_location)->left; - } while (smallest_location != NULL); + BinaryTreeNode* parent = node; + while (parent->left != NULL && (parent->left->left != NULL)) { + parent = parent->left; + } - return smallest_location; + return parent; } static int _BinaryTreeNode_UnlinkNode(BinaryTreeNode** nodep) @@ -179,11 +179,15 @@ static int _BinaryTreeNode_UnlinkNode(BinaryTreeNode** nodep) *nodep = (*nodep)->left; } else { // both right and left node active - BinaryTreeNode** smallest_subnode = _BinaryTreeNode_SmallestNodeLocation(*nodep); - BinaryTreeNode* right_branch = (*nodep)->right; - *nodep = *smallest_subnode; - *smallest_subnode = (*smallest_subnode)->right; - (*nodep)->right = right_branch; + BinaryTreeNode* smallest_parent = _BinaryTreeNode_SmallestNodeParent(*nodep); + BinaryTreeNode* smallest_node = smallest_parent->left; + + smallest_parent->left = smallest_node->right; + smallest_node->right = (*nodep)->right; + smallest_node->left = (*nodep)->left; + *nodep = smallest_node; + + _BinaryTreeNode_UpdateDepth(smallest_parent); } } @@ -225,6 +229,7 @@ static int _BinaryTree_Remove(BinaryTree* self, void* value) bottom_walker->position = BINARYTREENODEPOSITION_SELF; } + DynamicArray_Remove(&self->walker_stack, self->walker_stack.reserved - 1); _BinaryTree_DestroyNode(self, preserved_pointer); diff --git a/tests/BinaryTree.test.c b/tests/BinaryTree.test.c index 0508efa..902c7cf 100644 --- a/tests/BinaryTree.test.c +++ b/tests/BinaryTree.test.c @@ -216,6 +216,34 @@ void testMany(void) return; } +void testRanges(void) +{ + allocator_t allocator; + Allocator_CreateSystemAllocator(&allocator); + BinaryTree tree; + + assert(EXIT_SUCCESS == BinaryTree_Create( + &tree, + (BinaryTreeComparator) doublecomparator, + (void*) 0xDEADBEEF, + sizeof(double), + &allocator) + ); + + for (double value = 0; value < 300; value++) { + assert(EXIT_SUCCESS == BinaryTree_Insert(&tree, &value)); + } + + for (double value = 150; value <= 200; value++) { + assert(EXIT_SUCCESS == BinaryTree_Remove(&tree, &value)); + } + + BinaryTree_Destroy(&tree); + assert(allocator.reserved == 0); + + return; +} + int main() { testLifetime(); @@ -223,5 +251,6 @@ int main() testEqual(); testMany(); testRemoval(); + testRanges(); return 0; }