简体   繁体   中英

Deleting a node from Binary Search Tree in Java

I've been trying to delete a node from a BST. I'm taking help of two functions where one (findInorderSuccesor) is being called when a node has two Children. Problem is, the node that comes in as a replacement for the deleted node, is not getting deleted from it's original position. As a result, I've two nodes with the same value.

    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遍历树

As Boola wrote, You need to know the parent of the node You are deleting.

When you say focusNode = null; you only make the reference null, you don't remove the object from the tree, because the parent is still referencing that node. You need something like this:

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;
    }

and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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