二进制搜索树中的c ++ delete

时间:2011-12-24 12:47:10

标签: c++ binary-search-tree

我有一个二进制搜索树,包含以下节点:

struct ProductNode
{
    Product data;
    ProductNode* left;
    ProductNode* right;
};

我有一个删除函数,它接受ProductNode指针参数:

void ProductCategory::deleteandnull(ProductNode * p) 
{
    if(p!=NULL)
    {
        delete p;
        p=NULL;
    }
}

删除方法没问题。添加新叶子时左右指针为NULL但是当我使用此函数时,我看到没有删除,此操作不会更改二叉搜索树。那是什么问题?

3 个答案:

答案 0 :(得分:2)

改为使用:

void ProductCategory::deleteRightChild(ProductNode * p) 
{
    if(p->right!=NULL)
    {
        delete p->right;
        p->right = NULL;
    }
}

为左孩子写一个等效的函数。

您的功能不起作用,因为您不更改父节点的内容。它仍然有被删除节点的地址所以(如果这个内容在其他地方被真实地定位并且被更改)它可以访问它...!

但内存确实被释放了。

答案 1 :(得分:1)

编辑:这个答案是基于OP假设“没有删除”的假设,因为他期望在调用位置看到一个NULL指针。如果情况并非如此,他将需要澄清导致该结论的原因。因为没有理由认为OP的代码没有删除p指向的任何内容。

p按值传递到deleteandnull函数。因此,只有指针的本地副本设置为NULL。假设你在某处有这样的代码:

ProductNode *ptr = // Somehow initialize to the parent of the node to delete
.
.
deleteandnull(ptr->left);

您需要在调用deletandnull

后添加此内容
ptr->left = NULL;

请注意,在调用delete之前无需测试NULL。它会自己这样做。由于p中的deleteandnull是本地的,因此无需将其设置为NULL。所以整个代码也可以简化为:

ProductNode *ptr = // Somehow initialize to the parent of the node to delete
.
.
delete ptr->left;
ptr->left = NULL;

所有这一切,在现代C ++中,你不应该使用裸指针,newdelete。更喜欢使用智能指针,例如在Boost库中。

答案 2 :(得分:1)

name

C ++实现:

   Procedure :
   1. At first locate the node to be deleted.

   2. If the node is a leaf node :
   i. If the node is left child of the parent , make null the left pointer of its parent node and free the space for the node.
   ii. If the node is right child of the parent , make null the right pointer of its parent node and free the space for the node.

   3. If the node has one child
    i. If the node to be deleted is a left chile of its parent , then make link between the left pointer of its parent node and the child node to be deleted. Then delete the node.
    ii.If the node to be deleted is a right child of its parent , then make link between the right pointer of its parent node and the child node to be deleted. Then delete the node.

   4. If the node to be deleted has two child :
     i. Locate the node with maximum value from the left sub-tree of  the node to be deleted.
     ii. Replace the node value to be deleted by the node found in step 4(i)

   5. Now we get updated output