I am having a lot of trouble figuring out how to remove data from a BST using a double pointer and then changing the root if needed. This is what I am trying but when I test it it removes numbers that should not be removed...any idea on what is flawed?
EDIT: Below is my new code after the answer...
int removeBST(struct TreeNode** rootRef, int data)
{
while (*rootRef && (*rootRef)->data != data)
{
if ((*rootRef)->data > data)
{
rootRef = &(*rootRef)->left;
}
else if ((*rootRef)->data < data)
{
rootRef = &(*rootRef)->right;
}
}
if (*rootRef)
{
struct TreeNode *tmp = *rootRef;
if (rootRef->left == NULL && rootRef->right == NULL) // no children
{
free(tmp);
}
else if (rootRef->left->left == NULL && rootRef->right->right == NULL) // one child
{
rootRef = rootRef->left;
}
else
{
rootRef = inOrderSuccessor(rootRef);
removeBST(**rootRef, data);
}
return 1;
}
return 0;
}
*rootRef = tmp->left;you do keep the left pointer, but the ->right pointer will be orphanased, including the complete right subtree.