Fixed the sigsegv bug in binary tree

This commit is contained in:
vegowotenks 2024-10-13 22:05:41 +02:00
parent 88e4385c5f
commit 7c74b68d75
2 changed files with 45 additions and 11 deletions

View file

@ -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);