java - 将引用对象键设置为 null 无法按预期工作

标签 java binary-search-tree

我需要删除二叉搜索树的最小值,但我找不到一种干净的方法来做到这一点,目前我有一种干净的代码,尽管它没有像我期望的那样工作,我'我得到了这个代码(MTE有MTE左,MTE右和int val键):

MTE tempElement = root;

if(root == null) return;
else if((root.left == null) && (root.right == null))
{
    root = null;
    return;
}
else if(root.left != null)
{
    while(tempElement.left != null) tempElement = tempElement.left;

    if(tempElement.right == null)  tempElement = null;
    else tempElement = tempElement.right;
}
else if(root.right != null)
{
    if(tempElement.left == null) root = tempElement;
    else
    {
        while(tempElement.left != null) tempElement = tempElement.left;

        root.val = tempElement.val;
        if(tempElement.right == null) tempElement = null;
        else tempElement = tempElement.right;
    }
}

我在这段代码中遇到的问题是当我到达这行代码时 - if(tempElement.right == null) tempElement = null; 这是我的代码片段中的第 13 行假如。当我调试它时,它将 tempElement 更改为 null,但我的主根元素没有更改其任何节点 - 我期望它的工作方式,有任何解决方法吗?

最佳答案

例如,您应该保留指向父节点的指针,然后更改父节点的左或右指针

if(root.left != null)
{
    MTE prev = tempElement;
    while(tempElement.left != null) {
         prev = tempElement;
         tempElement = tempElement.left;
    }

    if(tempElement.right == null)  prev.left = null;
    else prev.left = tempElement.right;
}

也需要对 right != null 执行相同的操作。

关于java - 将引用对象键设置为 null 无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40725201/

相关文章:

java - 将 hibernate-validator 与 wicket 集成

java - 如何将节点随机插入二叉搜索树?

c - 二叉搜索树 : lost pointer in insertion function

binary-search-tree - 二叉搜索树可以既完整又完整吗?

c++ - BST 错误 : new initializer expression list treated as compound expression

algorithm - 在 O(n) 时间内将堆转换为 BST?

java - IDEA中的guava源代码有错误,怎么回事

Java WEKA API - StratifiedRemoveFolds

java - 当鼠标已经在按钮上时,鼠标监听器如何在一定时间后激活?

java - 在 ListView 中获取长按的内容