简体   繁体   中英

deleting node from a binary search tree

I am trying to create a function to delete a node from a binary search tree. I got the third case with node having 2 children working, but my code doesn't work it the node has 1 or no children.

Here is the code I copied directly from the book. Is this code I got from the book wrong?

template <class elemType>
void bSearchTreeType<elemType>::deleteFromTree
(nodeType<elemType>* &p)
{
nodeType<elemType> *current; //pointer to traverse the tree
nodeType<elemType> *trailCurrent; //pointer behind current
nodeType<elemType> *temp; //pointer to delete the node
if (p == NULL)
cout << "Error: The node to be deleted is NULL."
<< endl;
else if (p->lLink == NULL && p->rLink == NULL)
{
temp = p;
p = NULL;
delete temp;
}
else if (p->lLink == NULL)
{
temp = p;
p = temp->rLink;
delete temp;
}
else if (p->rLink == NULL)
{
temp = p;
p = temp->lLink;
delete temp;
}

Are you sure that your code is working perfectly with 2 children? Because the above snippet you provided only takes care of 3 cases: (1) no children, (2) 1 children pointed by left ptr, (3) 1 children pointed by right ptr... The last case, where there are 2 children, is simply not present...

So to answer your question: yes, the above code, as you provided, seems to be wrong (aka incomplete).

I managed to track down the source of what you are using. Do you have the following code inside the function shown above (appended after your stream of else if ), or is it absent?

else
{
    current = p->llink;
    trailCurrent = NULL;

    while(current->rlink != NULL)
    {
        trailCurrent = current;
        current = current->rlink;
    } //end while

    p->info = current->info;

    if(trailCurrent == NULL) //current did not move; 
                             //current == p->llink; adjust p
        p->llink = current->llink;
    else
        trailCurrent->rlink = current->llink;

    delete current;
}//end else

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM