簡體   English   中英

從二叉搜索樹中刪除節點

[英]deleting node from a binary search tree

我正在嘗試創建一個從二進制搜索樹中刪除節點的函數。 我得到了第三個案例,其中節點有2個子節點,但是我的代碼不起作用,該節點有1個子節點或沒有子節點。

這是我直接從書中復制的代碼。 我從書中得到的這段代碼錯誤嗎?

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;
}

您確定您的代碼可以與2個孩子一起正常工作嗎? 因為您提供的上述代碼片段僅能處理3種情況:(1)沒有孩子,(2)左ptr指向1個孩子,(3)右ptr指向1個孩子...最后一種情況,有2個孩子,根本不存在...

因此,請回答您的問題:是的,您提供的上述代碼似乎是錯誤的(aka不完整)。

我設法找到了您正在使用的內容。 上面顯示的函數中是否包含以下代碼(在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