java - 在Java中从二叉搜索树中删除节点

标签 java data-structures binary-search-tree

我一直在尝试从 BST 中删除节点。我正在使用两个函数,其中一个函数(findInorderSuccesor)在节点有两个子节点时被调用。 问题是,作为已删除节点的替代项出现的节点并未从其原始位置删除。结果,我有两个具有相同值的节点。

    obj.addNode(8);
    obj.addNode(2);
    obj.addNode(5);
    obj.addNode(1);
    obj.addNode(13);
    obj.addNode(10);
    obj.addNode(15);

    obj.deleteNode(obj.root,8);

    public void deleteNode(treeNode focusNode, int data)
    {
     if(data<focusNode.data)
        deleteNode(focusNode.left,data);
    else if (data>focusNode.data)
        deleteNode(focusNode.right,data);
    else
    {
        if(focusNode.right == null && focusNode.left == null)
            focusNode=null;
        else if(focusNode.left!=null && focusNode.right==null)
            focusNode = focusNode.left;
        else if (focusNode.right!=null && focusNode.left==null)
            focusNode = focusNode.right;
        else
        {
            //node has two children
            BSTDeletion obj = new BSTDeletion();
            treeNode replacement =obj.findInorderSuccessor(focusNode.right);
            focusNode.data = replacement.data;
            deleteNode(focusNode.right, replacement.data);

        }
    }
}



public treeNode findInorderSuccessor(treeNode focusNode)
{
treeNode preFocusNode = null;
 while(focusNode!=null)
 {
    preFocusNode = focusNode;
    focusNode = focusNode.left;
 }
return preFocusNode;
}

BFS Traversal of the Tree

最佳答案

正如 Boola 所写,您需要知道要删除的节点的父节点。

当你说 focusNode = null;您只需将引用设为空,就不会从树中删除该对象,因为父节点仍在引用该节点。 你需要这样的东西:

public void deleteNode(treeNode focusNode, int data)
{
 if(data<focusNode.data)
    deleteNode(focusNode.left,data);
else if (data>focusNode.data)
    deleteNode(focusNode.right,data);
else
{
    treeNode parent = focusNode.getParent();  // get the parent.
if(focusNode.left==null && focusNode.right==null) 
    {
        if(parent.left.equals(focusNode))
             parent.left = null;                //Set the parents reference to null. 
        else
             parent.Right = null;
    }
 else if(focusNode.left!=null && focusNode.right==null)
    {
        if(parent.left.equals(focusNode))
             parent.left = focusNode.left;  //Reassign the parents reference to the correct node. 
        else
             parent.right = focusNode.left;
    }

等等。

关于java - 在Java中从二叉搜索树中删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41015171/

相关文章:

java - OnActivityResult不是调用内部fragment而是调用android中的Main Activity

C++删除节点二叉搜索树

javascript - 如何构建特定时间的数据以便找到最近的点?

c++ - 二叉搜索树,如何将节点连接到根?

java - 导入数据库驱动

java - java应用程序类路径中的XML文件是否总是加载到内存中?

java - 访问/查找 HashMap 存储桶(不是存储桶中的值)的时间复杂度是多少?

java - 遍历二叉搜索树

java - 如何为二叉搜索树中存储的字符串编写查找前缀和查找单词方法?

java - java.lang.Thread 中新增的附加字段,是什么意思?