【问题标题】:Inserting right children on left side of BST, and vice versa在 BST 的左侧插入右孩子,反之亦然
【发布时间】:2011-11-27 19:13:44
【问题描述】:

我在这个家庭作业中的插入方法有点困难。我已经完成了大部分工作,但是由于某种原因,每当我的程序应该在树的左侧插入一个节点作为右子节点时,它只是将它作为左子节点插入。

我有点用一种奇怪的方式进行比较(很多符号应该颠倒,但出于某种原因它会这样工作)所以如果您在阅读它时有困难,请多多包涵。

我知道这是实现二叉搜索树的一种可怕方式,我永远不会在现实世界中这样做,但这是家庭作业,因此——我别无选择。

一如既往地感谢任何和所有帮助。谢谢!

编辑:我知道现在问题出在哪里。它在 searchFor() 方法中。它不是节点的合法父节点,而是使父节点成为树的根(在这种情况下,节点的父节点始终是“杯子”。)

既然已经解决了,谁能提供一个解决方案?

Edit2:删除了一些我认为与问题无关的额外内容。我很确定我已将其范围缩小到 searchFor() 方法。每当我调用返回当前节点的父节点时,它都会返回树的根(“杯子”)。我认为这就是我遇到问题的原因,因为它基于它插入。

感谢到目前为止的所有帮助,我真的很感激。

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

}

【问题讨论】:

  • 这是很多代码 - 你不知道哪里出了问题吗?您是否使用调试器单步执行?
  • 很确定我的问题来自我在 Binary Search Tree 类中的 insert 方法,但我想我会提交所有内容以防万一有人想查看所有内容。

标签: java search binary-tree


【解决方案1】:

BinarySearchTree 的compare(x, y) 方法错误。 它将节点与数据进行比较,比较器用于将数据与数据进行比较。将“对象”更改为“字符串”,当您的示例数据是字符串时,它将无法编译。

这应该可以解决它:

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

【讨论】:

  • 我认为你犯了那个错误,但我真的不知道是否还有更多问题。您的代码太长了...您应该选择重现问题所需的最少和更简短的代码,并仅检查该代码。如果您无法解决,请仅使用该代码询问。
  • 欣赏它,伙计!但我不认为这是引起重大关注的原因(在那之前它似乎工作正常。)我相当有信心我的问题出在 searchFor() 方法中。我很感激!
  • 如果我是对的并且这不是问题,请在问题代码中进行编辑。如果你这样做,你应该在这里评论你改变了它,所以我的回答看起来并不愚蠢。谢谢。
  • 我相应地编辑了我的问题。我很确定我的问题出在我的程序中。但是,再次感谢您。
【解决方案2】:

在您的 SearchResult 类中,您是否有确定交换左插入或右插入的方法?

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

如果 compare 大于 0,它应该作为一个正确的孩子感兴趣,对吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多