In the chapter on binary search tree’s in CLRS and I encountered the transplant function which replaces a node u with node v with appropriate changes in the parent element.
Here is the code I wrote for transplant function:
void transplant(Node* root, Node* u, Node* v)
{
if(u->parent == NULL)
root = v;
else if(u == u->parent->left)
u->parent->left = v;
else
u->parent->right = v;
if(v != NULL)
v->parent = u->parent;
}
It’s not that I don’t understand how this works but that why this works. When I make a function call I’m basically sending a copy of pointers root, u, v to the function right ? so the changes made in the function shouldn’t actually reflect on the root unless I return it or use pointer to pointer type but its actually changing the original root. I defined root as global variable, does that change anything ?
The function will not work if
u->parentisNULL, in that case, only the local variablerootis set tov, nothing accessible from outside the function changes.If
u->parent != NULL, thenu->parent->leftandu->parent->rightare the members of theNodepointed to byu->parent, and those are overwritten, so the changes are visible inmain.