as a n exercise i am working on a binary search tree. I have managed to search through the binary tree, and add nodes, but now that i try to find a way to delete, i seem to be stuck at how to determine who is the parent of a node that is to be deleted.
So to start with i have this structure
struct BST_node {
struct double_linked_list *data;
struct BST_node *left;
struct BST_node *right;
};
and i have also a pointer for this structure that points to root..
struct BST_node *BST_email_root = 0;
I have this function to search for a Node
struct BST_node *BST_find_customer(struct BST_node *root, char *email) {
if (root==NULL)
return NULL;
if (strcmp(email,root->data->data->email)==0)
return root;
else
{
if (strcmp(email,root->data->data->email)==-1)
return BST_find_customer(root->left,email);
else
return BST_find_customer(root->right,email);
}
that i call inside other functions, by using
b = BST_find_customer(BST_email_root, email);
and i am trying to create the function to delete nodes..What i have to is this:
struct BST_node *BST_delete(struct BST_node *root, char *email)
{
struct BST_node *temp;
if (root==NULL)
return root;
else if(strcmp(root->data->data->email,email)>0)
root->left = BST_delete(root->left, email);
else if(strcmp(root->data->data->email,email)<0)
root->right = BST_delete(root->right, email);
else
{
if(root->left == NULL && root->right == NULL)
{
free(root);
root = NULL;
}
else if(root->right == NULL)
{
temp = root;
root = root->left;
free(temp);
}
else if(root->left == NULL)
{
temp = root;
root = root->right;
free(temp);
}
else
{
struct BST_node *maxNode = findMaxNode(root->left);//finding the maximum in LEFT sub-tree
root->data = maxNode->data; //Overwriting the root node with MAX-LEFT
root->left = BST_delete(root->left, maxNode->data);//deleted the MAX-LEFT node
}
return root;
}
}
by using this function also
struct BST_node *findMaxNode(struct BST_node *root)
{
if(root->right == NULL) return root;
findMaxNode(root->right);
}
However this doesnt work also and i get errors