从Java

时间:2016-12-07 10:36:15

标签: 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

1 个答案:

答案 0 :(得分:0)

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

当你说focusNode = null;您只将引用设为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;
    }

等等。