函数从二进制搜索树中删除具有给定值的节点

Function to delete node with given value from a binary search tree

本文关键字:节点 二进制 搜索树 删除 函数      更新时间:2023-10-16

我有一个名为TreeNode的结构,它有一个int键、左键、右键和父键。我正试图用DeleteNode函数从树中删除一个节点,但它不起作用。我应该用左子树中的最大值替换DeleteNode函数中删除的节点。我的移植函数和max函数是DeleteNode的辅助函数。我的问题是,我不确定在DeleteNode函数中,我应该在哪里将我所处的节点值与我通过该函数传递的值进行比较。我在代码中有一条带星号的注释,我不知道该怎么办。如果有任何帮助,我们将不胜感激!

void transplant(TreeNode* u, TreeNode* v)   //swaps u with v
{
if (u->parent == NULL)  //if u was root, make v new root
    u->parent = v;
else if (u == u->parent->left)  //if u is smaller than it's parent
    u->parent->left = v;        //set v to the left child of parent of u. Swap them at left, really
else
    u->parent->right = v;       //otherwise swap them at right
if (v != NULL)              //reassign parents to double link
    v->parent = u->parent;
}
TreeNode* maximum(TreeNode* n)
{
while (n->left != NULL)
    n = n->left;
return n;
}
  void deleteNode(TreeNode *node, int key)
{
if (node->left == NULL)                 //if there is no left child
    transplant(node, node->right);      //swap 
else if (node->right == NULL)           //if there is no right child
    transplant(node, node->left);       //swap 
else 
{
  if(node->key == key){ //****This if comparison must be wrong***
    TreeNode* temp = maximum(node->right);  //make temp the max on right
    if (temp->parent != node )              //if it is more than one chain down
    {
        transplant(temp, temp->right);          //swap temp and it's right branch
        temp->right = node->right;          //set right branch to nodes right
        temp->parent->right = temp;             //set temp to the right child 
    }
    transplant(node, temp);                 // transplant
    temp->left = node->left;                //get nodes left branch
    temp->left->parent = temp;              //replace
    }
}
}

首先,您有三种情况需要处理:(直接来自维基百科。当我采用数据结构时,这对我来说很好)

有三种可能的情况需要考虑:

删除没有子节点(叶子):只需从树中删除该节点。

删除具有一个子节点的节点:删除该节点并将其替换为其子节点。

删除有两个子节点的节点:调用要删除的节点N。不要删除N。相反,选择其按顺序的后续节点或按顺序的前一个节点R。将R的值复制到N,然后在R上递归调用delete,直到达到前两种情况之一。

一般来说,带有子节点的节点更难删除。与所有二叉树一样,节点按顺序的后继节点是其右子树最左边的子节点,节点按次序的前导节点是左子树最右边的子节点。在任何一种情况下,此节点都将有零个子节点或一个子节点。根据上面两个较简单的情况之一删除它。

由于最大值(node->right),您似乎正在尝试实现按顺序的后续选项。

现在我们已经确定了你可能的病例,在我看来,唯一真正需要移植的病例是第三个病例,有两个孩子。

情况1:只需在叶节点上调用delete。

案例2:

这里,del是要删除的节点(在本例中,del有一个右子节点)。我只是写得很快。第一个if语句检查del是否是其父节点的左子节点,然后通过将其父节点指向其子节点将其从指针等式中"移除",反之亦然。第二个if执行相同的操作,但检查del是否是其父节点的正确子节点。最后,删除节点。

del->right->parent = del->parent;
if (del == del->parent->left)
    del->parent->left = del->right;
else if (del == del->parent->right)
    del->parent->right = del->right;
delete del;

案例3:

TreeNode *inOrderSuccessor = maximum(del->right);
del->val = inOrderSuccessor->val; //you could use transplant/swap here
deleteNode(inOrderSuccessor, inOrderSuccessor->val);

仅此而已。