简体   繁体   English

在BST的左侧插入正确的子级,反之亦然

[英]Inserting right children on left side of BST, and vice versa

I'm having a little bit of difficulty with my insert method for this homework assignment. 我在此作业分配中的插入方法遇到一些困难。 I have most of it done, but for some reason whenever my program is supposed to insert a node as a right child on the left side of the tree it just inserts it as a left child. 我已经完成了大部分工作,但是由于某种原因,每当我的程序应该在树的左侧插入一个节点作为右子节点时,它只是将其作为左子节点插入。

I kind of do my comparison in a weird way (signs should be reversed for a lot of them, but it worked like that for some reason) so please bear with me if you have difficulty in reading it. 我有点怪异的比较方式(很多符号应该颠倒过来,但是由于某种原因它确实起作用了),所以如果您阅读困难,请多多包涵。

I know that this is a horrible way to implement a binary search tree, and I would never ever do it in the real world, but it's homework and thus -- I have no choice. 我知道这是实现二进制搜索树的可怕方法,我永远都不会在现实世界中这样做,但这是家庭作业,因此-我别无选择。

Any and all help is appreciated, as always. 一如既往地感谢所有帮助。 Thank you! 谢谢!

Edit: I know where the problem is now. 编辑:我知道问题出在哪里。 It's within the searchFor() method. 它在searchFor()方法中。 Instead of the node's rightful parent, it makes the parent the root of the tree (in this case the parent of the node is always "cup".) 它使该节点的父节点成为树的根,而不是该节点的合法父节点(在这种情况下,该节点的父节点始终为“ cup”。)

now that that's out of the way, can anyone offer up a solution? 既然那已经成为现实,任何人都可以提供解决方案吗?

Edit2: Took some of the extra stuff out that I don't think is relevant to the problem. Edit2:从我认为与问题无关的一些额外的东西。 I'm pretty sure I've narrowed it down to the searchFor() method. 我很确定我已经将其范围缩小到searchFor()方法。 Whenever I call to return the parent of the current node, it will return the root of the tree ("cup.") I think that's why I'm having my problems, since it inserts based on that. 每当我调用返回当前节点的父节点时,它将返回树的根(“ cup”)。我认为这就是我遇到问题的原因,因为它是基于此插入的。

Thanks for all the help so far, I really appreciate it. 感谢到目前为止的所有帮助,我非常感谢。

public class BinarySearchTree //implements Comparator
{
private Comparator<Object> dataComparator;
private LinkedListWithTwoLinks tree;

public static void main (String[] args)
{
    BinarySearchTree bst;
    Object hold;
    String[] words = {"cup", "shaker", "cord", "key", "addressbook", "date", "address", "cupcake",
    "card", "tape", "page", "day", "key", "days", "dayt"};

    bst = new BinarySearchTree(new AlphabeticComparator());
    System.out.println("[1]: original tree");
    for(int i=0; i<words.length; i++) if (!bst.insert(words[i])) { System.out.println(">>>>>>>>>>>>> " + words[i] + " is already in tree"); }
    bst.inOrder();

    }

    public static class AlphabeticComparator implements Comparator <Object>
    {
    public int compare(Object x, Object y)
    {
    if ( x == y ) return 0;
    if ( x == null) return -1;
    if ( y == null) return 1;
    return (x.toString().compareTo(y.toString()));
    }
    }


    public static class LastCharacterComparator implements Comparator <Object>
    {
    public int compare(Object x, Object y)
    {
    String xs;
    String ys;

    if ( x == y ) return 0;
    if ( x == null ) return -1;
    if ( y == null) return 1;

    xs = x.toString();
    ys = y.toString();

    if ( xs.length() == 0) return -1;
    if ( ys.length() == 0) return 1;

    return (xs.charAt(xs.length()-1) - ys.charAt(ys.length()-1));
    }
}

public BinarySearchTree(Comparator<Object> y)
{
    dataComparator = y;
    this.tree = new LinkedListWithTwoLinks();
}

private int compare(BinarySearchTreeElementInterface s, Object data)
{
    return this.dataComparator.compare(s, data);
}


public boolean insert(Object data)
{
    boolean success;
    BinarySearchTreeElementInterface current;
    BinarySearchTreeElementInterface parent;
    current = getRoot();
    parent = null;
    success = false;
    if (current == null)
     {
        getTree().insert(data);
        return true;
     }

    else 
    {
        SearchResult insert;
        insert = searchFor(data);
        //if (data == "shaker") {System.out.println(insert.resultOfCompare); }
        while (current != null)
        {
            if (insert.insertAsLeftChild())
            {
                //if (data == "card") {System.out.println("IN RIGHT");}
                //System.out.println("IN LEFT");
                parent = current;
                current = current.getLeftChild();
            }

            else if (insert.insertAsRightChild())
            {
                //if (data == "card") {System.out.println("IN RIGHT");}
                parent = current;
                current = current.getRightChild();
            }

        }

        if (insert.insertAsLeftChild())
        {
            //parent.setLeftChild(insert.getParentOfLocation()); //insert.getParentOfLocation()
            //System.out.println(data);
            getTree().insertUsingPrior(parent, data);
            //System.out.println(insert.getParentOfLocation()+" bye left");
        //  System.out.println(insert.getLocation()+" hi");
            success = true;
        }

        else if (insert.insertAsRightChild())
        {
            //parent.setRightChild(insert.getParentOfLocation());
            //System.out.println(data);
            getTree().insertUsingNext(parent, data);
            //System.out.println(insert.getParentOfLocation()+" bye right");
        //  System.out.println(insert.getLocation());
            success = true;
        }

        else {success = false;}
        /*
        figures out if it should be inserted as a left or right child
        then call insert using prior/next
        }*/
    }

    return success;
}


private SearchResult searchFor(Object data)
{
    /*returns either to node containing the data or the parent of the node of which the data would be a child of*/
    if (getTree() == null) {throw new ListEmptyException("Tree is empty!");}
    BinarySearchTreeElementInterface currentLocation;
    BinarySearchTreeElementInterface parent;
    SearchResult destination;
    parent = getRoot();
    currentLocation = parent;


    while (currentLocation != null)
    {
        if (currentLocation.getData() == data)
        {
            return new SearchResult(parent, currentLocation, compare(currentLocation, data));
        }

        if (compare(currentLocation, data) < 0)
        {
            //System.out.println("IN LEFT");
            parent = currentLocation;
            currentLocation = currentLocation.getLeftChild();
        }

        else if (compare(currentLocation, data) > 0)
        {
            //System.out.println("IN RIGHT");
            parent = currentLocation;
            currentLocation = currentLocation.getRightChild();
        }


    }


    destination = new SearchResult(parent, currentLocation, compare(parent, data));
    //System.out.println(destination.resultOfCompare);
    return destination;
    /*
     * use nothing but BSTEIs
    */
}

public void inOrder()
{
    inOrder(getRoot());
}

public void inOrder(BinarySearchTreeElementInterface BSTroot)
{

    //System.out.println(BSTroot.getRightChild());
    if (BSTroot != null)
    {
        inOrder(BSTroot.getLeftChild());
        System.out.println(BSTroot.getData());
        inOrder(BSTroot.getRightChild());
    }

    /*if (BSTroot.getLeftChild() != null)
    {

    }
    System.out.println(BSTroot.getData());
    if (BSTroot.getRightChild() != null)
    {
        inOrder(BSTroot.getRightChild());
        //System.out.println(BSTroot.getData());
    }
    System.out.println(BSTroot.getData());*/
}

public int size()
{
    return tree.size();
}
/*SEARCH RESULT CLASS-----------------------------------------------------------------------------------------*/
    public class SearchResult
    {
        BinarySearchTreeElementInterface location;
        BinarySearchTreeElementInterface parentOfLocation;
        int resultOfCompare;

        public SearchResult(BinarySearchTreeElementInterface parent, BinarySearchTreeElementInterface locate, int comp)
        {
            this.parentOfLocation = parent;
            this.location = locate;
            this.resultOfCompare = comp;

        }

        public BinarySearchTreeElementInterface getLocation()
        {
            return this.location;
        }

        public BinarySearchTreeElementInterface getParentOfLocation()
        {
            return this.parentOfLocation;
        }

        public boolean insertAsLeftChild()
        {
            if (resultOfCompare > 0) {return true;}
            else {return false;}
        }

        public boolean insertAsRightChild()
        {
            if (resultOfCompare < 0) {return true;}
            else {return false;}
        }

        public boolean locationIsLeftOfParent()
        {
            return this.location == parentOfLocation.getLeftChild();
        }

        public boolean locationisRightOfParent()
        {
            return this.location == parentOfLocation.getRightChild();
        }

        public boolean wasSearchSuccessful()
        {   
            return this.parentOfLocation == this.location;
        }

        public void setLocation(BinarySearchTreeElementInterface newLocation)
        {
            this.location = newLocation;
        }

        public void setLocationOfParent(BinarySearchTreeElementInterface newParentLocation)
        {
            this.parentOfLocation = newParentLocation;
        }
    }

}

compare(x, y) method of BinarySearchTree is wrong. BinarySearchTree的compare(x,y)方法错误。 It compares a node to a data with a comparator made to compare data against data. 它使用比较器将节点与数据进行比较,以将数据与数据进行比较。 Change 'Object' to 'String' and it will not compile while your sample data are strings. 将“对象”更改为“字符串”,当您的示例数据为字符串时,它将不会编译。

This should fix it: 这应该解决它:

private int compare(BinarySearchTreeElementInterface s, Object data)
{
    return this.dataComparator.compare(s.getData(), data);
}

In your SearchResult class, do you have the way it determines a left or right insert swapped? 在SearchResult类中,您是否具有确定左插入或右插入的方式?

public boolean insertAsLeftChild()
{
    if (resultOfCompare > 0) {return true;}
    else {return false;}
}

If the compare is greater than 0, it should be interested as a right child, correct? 如果比较值大于0,则应该将其作为正确的子对象感兴趣,对吗?

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

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