This is a simple node remove function from a binary tree, and now I want to change the removeElement
function to void
instead. At least from what I gathered, most tutorials out there don't cover how to do this.
Base Code:
struct treeNode* removeElement(struct treeNode *root, int data)
{
if(root==NULL)
return NULL;
if (data>root->data)
root->right = removeElement(root->right, data);
else if(data<root->data)
root->left = removeElement(root->left, data);
else
{
if(root->left==NULL && root->right==NULL)
{
free(root);
return NULL;
}
else if(root->left==NULL || root->right==NULL)
{
struct treeNode *temp;
if(root->left==NULL)
temp = root->right;
else
temp = root->left;
free(root);
return temp;
}
else
{
struct treeNode *temp = find_minimum(root->right);
root->data = temp->data;
root->right = removeElement(root->right, temp->data);
}
}
return root;
}
what I have tried
void removeElement(struct treeNode **root, int data)
{
if(*root==NULL)
return;//dont know if this is correct
if (data>(*root)->data)
removeElement(&(*root)->right, data);
else if(data<(*root)->data)
removeElement(&(*root)->left, data);
else
{
//dont know how to continue
if((*root)->left==NULL && (*root)->right==NULL)
{
}
else if(*root)->left==NULL || *root)->right==NULL)
{}
My main problems are I don't know how the code should look like because I cant return in void
, so the recursion becomes tricky for me. If anyone would help me with the else if(*root)->left==NULL || *root)->right==NULL)
I believe I can manage the rest.
I don't know if this a valid question/answered before. If it is not, let me know. I will try to improve it or delete the question if needed. I appreciate any help you can provide.
you sent a pointer to the 'left' or to 'right' which are members of the parent node for this leaf. So, you just need to free it and to NULLify, something like the following:
if((*root)->left==NULL && (*root)->right==NULL)
{
free(*root);
*root = NULL;
return;
}
In the second part, if the node has only a single child, according to your algorighm, this child gets reassigned to the corresponding brabch of the parent. I think, the following is correct:
else if((*root)->left==NULL || (*root)->right==NULL)
{
struct treeNode *temp;
if(root->left==NULL)
temp = (*root)->right;
else
temp = (*root)->left;
free(*root);
*root = temp; // << assign temp to the parents left or right
return ;
}