简体   繁体   English

从二叉搜索树中删除节点

[英]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. 我得到了第三个案例,其中节点有2个子节点,但是我的代码不起作用,该节点有1个子节点或没有子节点。

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? 您确定您的代码可以与2个孩子一起正常工作吗? 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... 因为您提供的上述代码片段仅能处理3种情况:(1)没有孩子,(2)左ptr指向1个孩子,(3)右ptr指向1个孩子...最后一种情况,有2个孩子,根本不存在...

So to answer your question: yes, the above code, as you provided, seems to be wrong (aka incomplete). 因此,请回答您的问题:是的,您提供的上述代码似乎是错误的(aka不完整)。

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 if串之后添加),或者不存在?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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