简体   繁体   English

从二叉搜索树中删除元素

[英]Deleting elements from a binary search tree

I am currently writing a method that removes a given value from a binary search tree. 我目前正在编写一种从二叉搜索树中删除给定值的方法。 However when I call it, it deletes the said value but then duplicates every other value. 但是,当我调用它时,它会删除上述值,然后再复制其他所有值。 I have no idea why. 我不知道为什么。 Please tell me what is wrong. 请告诉我有什么问题。 There are two methods, one that find the elements, and the other that deletes it. 有两种方法,一种找到元素,另一种删除元素。 Here is the one that finds that element... 这是找到该元素的那个...

public static TreeNode delete(TreeNode t, Comparable x, TreeDisplay display)
{
    if( x.compareTo(t.getValue()) > 0)
        {
             display.visit(t);

             t.setRight(delete( t.getRight(), x, display));

    }
    else if ( x.compareTo(t.getValue()) < 0)
    {
        display.visit(t);

        t.setLeft(delete(t.getLeft(), x, display));
    }
    else
    {
        t = deleteNode(t, display);
    }

    return t;

This is the method that deletes the value 这是删除值的方法

private static TreeNode deleteNode(TreeNode t, TreeDisplay display)
  {

    if (t.getRight()!=null)
    {
        TreeNode right = t.getRight();
        TreeNode max = (TreeNode)TreeUtil.leftmost(right);
        TreeNode previous = null;
        while ( right.getLeft()!=null&&right.getLeft().getLeft()!=null)
        {
            right = right.getLeft();
        }
        t.setValue(max.getValue());
        if ( max.getRight()==null)
        {
            right.setLeft(null);
        }
        else
        {
            right.setLeft(max.getRight());
        }
    }
    else if (t.getLeft() !=null)
    {
        TreeNode left = t.getLeft();
        TreeNode max = (TreeNode)TreeUtil.rightmost(left);
        while(left.getRight()!=null &&left.getRight().getRight()!=null)
        {
            left = left.getRight();
        }
        t.setValue(max.getValue());
        if ( max.getLeft()==null)
        {
            left.setRight(null);
        }
        else
        {
            left.setRight(max.getLeft());
        }
    }
    else
    {
        t = null;
    }
    return t;
}

Thanks in advance! 提前致谢!

...it deletes the said value but then duplicates every other value. ...它删除了所述值,但随后每隔一个值重复一次。 I have no idea why. 我不知道为什么。 Please tell me what is wrong. 请告诉我有什么问题。

It's because you're returning the deleted node from deleteNode() , and in the first method delete() , your calls to setRight() and setLeft() are setting every traversed element to the deleted element as the recursion unwinds back up the tree. 这是因为您要从deleteNode()返回已删除的节点,并且在第一个方法delete() ,您对setRight()setLeft()调用setLeft()每个遍历的元素都设置为setLeft()元素,因为递归可以使树退回。

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

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