简体   繁体   English

如何从二叉搜索树中删除节点

[英]How do I delete a node from a binary search tree

How do I implement a function to delete a node from a binary search tree? 如何实现从二进制搜索树中删除节点的功能? Below is my current function: 下面是我当前的功能:

    void makeDeletion(TreeNode *&tree) {
    TreeNode *NodeToDelete;
    NodeToDelete = tree;
    TreeNode *InOrder;

    if (tree->right == NULL && tree->left == NULL) {
        delete NodeToDelete;
    }
    if (tree->right == NULL) {
        tree = tree->left;
        delete NodeToDelete;
    }
    else if (tree->left == NULL) {
        tree = tree->right;
        delete NodeToDelete;
    }
    else {
        InOrder = tree->right;
        while (InOrder->left != NULL) {
            InOrder = InOrder->left; 
        }

        NodeToDelete->value = InOrder->value;
        remove(InOrder, InOrder->value);
    }
}

And here is the remove function I have that locates the value to be deleted: 这是我具有的remove功能,用于定位要删除的值:

    void remove(TreeNode *&tree, ANY num) {//Removed Need for ">"
    if (tree == NULL){
        return;
    }

    if (tree->value == num) {
        makeDeletion(tree);
    } else if (num < tree->value) {
        remove(tree->left, num);
    } else {
        remove(tree->right, num);
    }
};//Remove

As it stands I feel like I'm very close, but when I go to output the contents of the binary tree the program crashes. 就目前而言,我感觉自己已经很接近了,但是当我输出二进制树的内容时,程序崩溃了。 I am trying to use an approach where, if the node has two children, I locate the in order successor, swap the values of the nodes of the in order successor and the node to be "deleted," and then delete the in order successor. 我正在尝试使用一种方法,如果该节点有两个孩子,则找到顺序继承者,交换顺序继承者和要“删除”的节点的节点值,然后删除顺序继承者。 Without adjusting the remove function, what bit of information am I missing to make the makeDeletion function work as described? 如果不调整remove函数,那么使makeDeletion函数如所描述的makeDeletion工作,我会丢失什么信息?

EDIT: in the makeDeletion function I mistakenly wrote two if statements in succession. 编辑:在makeDeletion函数中,我错误地连续写了两个if语句。 The second if statement should be an else if statement. 第二个if语句应该是else if语句。

In makeDeletion , if tree is a leaf (both left and right are NULL ), you delete the leaf node, and don't set tree = nullptr . makeDeletion ,如果tree是叶(包括leftrightNULL ),你删除叶节点,并且不设置tree = nullptr This leaves a dangling reference in your tree to memory that has been freed. 这会将悬空的引用留在树中,以释放已释放的内存。 Also, you then dereference the (now deleted) node in the next if . 另外,然后在下一个if取消引用(现在已删除)节点。 Either one of these can result in your crash. 其中任何一种都可能导致崩溃。

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

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