树删除节点节点

2023-09-11 23:28:40 作者:此后,你我终年不遇

我试图完成删除功能。

下面是伪code,注意结尾:

我不知道是不是伪code是错误的,但。

下面是我如何跨preTED是:

 节点* minNode =最小(toDelete->右一);

            INT TMP = 0;
            TMP = minNode-> VAL;
            //删除(安培; TMP);
            免费(minNode);
            minNode = NULL;
            toDelete-> VAL = TMP;
 
万字文 通过分析 JDK 源代码研究 TreeMap 红黑树算法实现

只有一次,它会删除它,它开始打印时填充万亿零。

是我在做什么做有意义吗? 的code我剩下的就是对的,不然我这么认为反正。它只螺丝在这种情况下。

下面是最小的功能以及

 节点* BST ::最低(节点* CURR){

    //如果(curr->!左= NULL){
    //返回(最低(curr->左));
    //}
    //返回CURR;
    节点*节点= CURR;
    而(与于节点GT;!左= NULL){
        节点=  - 于节点GT;左;
    }
    返回节点;

}
 

解决方案

这是一些可怕的伪code和一目了然它甚至不看的权利(如果这是一个二叉搜索树,因为 BST 将表明,然后圈出部分是错误的)。有一个关于二叉搜索树在互联网上提供更好的信息。

在任何情况下,你想找到的右子树最小的元素,因为这将是比所有的右子树的其他元素比所有的左子树的其他元素较少,但更大。

看起来你的最小功能是正确的。您需要在释放后,以删除提及minNode。因此,(minNode->母公司) - >左 = NULL或一些稍微繁琐,如果你没有一个父指针。现在的离开只是指向内存中的空白区域,导致完全随机的行为。

I am trying to finish the delete function.

Here is the pseudo code, notice the end:

I don't know if the pseudo code is wrong though.

Here is how I interpreted it:

Node* minNode = Minimum(toDelete->right);

            int tmp = 0;
            tmp = minNode->val;
            // delete(&tmp);
            free(minNode);
            minNode=NULL;
            toDelete->val=tmp;

except once it deletes it, it starts filling a trillion zeroes when printing.

Is what I am doing making sense? The rest of the code I have is right, or I think so anyway. It only screws up in this scenario.

Here's the minimum function as well

Node* BST::Minimum(Node *curr) {

    // if (curr->left != NULL) {
    //      return(Minimum(curr->left));
    //  }
    //  return curr;
    Node* node = curr;
    while (node->left != NULL) {
        node = node->left;
    }
    return node;

}

解决方案

That is some terrible pseudocode, and at a glance it didn't even look right (if this is a binary search tree, as BST would indicate, then the circled part is wrong). There is much better information about binary search trees available on the internet.

At any rate, you're trying to find the smallest element in the right subtree, since that will be less than all the other elements in the right subtree but greater than all the other elements in the left subtree.

Looks like your minimum function is right. You need to delete the reference to minNode after you free it. So (minNode->parent)->left = NULL or something slightly more tedious if you don't have a parent pointer. Right now that left just points to an empty space in memory, leading to completely random behavior.