这些是我的领域:

public class BSTSet <E> extends AbstractSet <E> {

    // Data fields
    private BSTNode root;
    private int count = 0;
    private Comparator<E> comp;   // default comparator

    /** Private class for the nodes.
     *  Has public fields so methods in BSTSet can access fields directly.
     */
    private class BSTNode {

        // Data fields

        public E value;
        public BSTNode left = null;
        public BSTNode right = null;

        // Constructor

        public BSTNode(E v) {
            value = v;
        }

        //creates a method called contains so that i can call it later on for my find method
        public boolean contains(Object item) {
            return contains(item);//root.value.equals(item);
        }

        public int height() {
            return height();
        }

    }
    // Constructors - can either use a default comparator or provide one
    public BSTSet() {
        comp = new ComparableComparator();      // Declared below
    }

    public BSTSet(Comparator <E> c) {
        comp = c;
    }
}


这就是我要完成的工作:

private class BSTSetIterator implements Iterator<E> {

    private Stack<BSTNode> stack = new Stack<BSTNode>();
    private BSTNode current = root;

    public BSTSetIterator(BSTNode root) {

         return new BSTSetIterator();

    }

    public boolean hasNext() {

        boolean hasNext = false;
        hasNext = !stack.isEmpty() || current != null;
        return hasNext;

    }

    public E next() {

        BSTNode next = null;

        while (current != null) {
            stack.push(current);
            current = current.left;
        }
        next = stack.pop();
        current = next.right;

        return next;

    }

    public void remove() {
        throw new UnsupportedOperationException();
    }
}
// Comparator for comparable

private class ComparableComparator implements Comparator<E> {
    public int compare(E ob1, E ob2) {
        return ((Comparable)ob1).compareTo(ob2);
    }
}


到目前为止,代码在return new BSTSetIterator();return next;行处失败。对于return next,它表示返回的数据类型错误。我将如何解决这些方法,以便可以使用Stack遍历BST?

最佳答案

BSTSetIterator();


这是行不通的,因为您的构造函数需要一个根,而您没有传递该参数。如果您有一个名为“ tree”的BSTSet对象,并且想要创建一个新的迭代器,则应使用以下方式创建迭代器:

BSTSetIterator iterator = new BSTSetIterator(tree.getRoot());


但是,您的BSTSet类中没有getter,并且您的根是私有的。不用担心,该问题的解决方案是在BSTSetIterator类内创建一个公共getter,如下所示:

public BSTNode getRoot()
{
    return this.root;
}


构造函数不返回值,这是不正确的:

 public BSTSetIterator(BSTNode root) {
         return new BSTSetIterator();
    }


相反,可以这样编写您的构造函数:

public BSTSetIterator(BSTNode root)
{
    this.current = root;
}


另外,此定义是不正确的,因为根目录无法访问:

private BSTNode current = root;


您应该改为:

private BSTNode current;


至于你的其他问题,

BSTNode next = null;


表示您的变量“ next”属于BSTNode类型。

public E next()


表示您称为next的方法为E类型。由于E和BSTNode不相同,您的返回:

return next;


是不正确的。我可以为您提供更多帮助,但是我已经意识到您正在学习这种语言,最好让您从总体上探索技术和编程,因为这样您会变得更快。 “给一个人一条鱼,你就给他喂一天。教一个人如何钓鱼,你就给他一辈子。”

10-07 19:02
查看更多