2012-10-08 104 views
0

这些都是我的领域:迭代方法BST

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,它表示它返回的数据类型是错误的。我将如何去修复这些方法,以便我可以使用堆栈遍历BST?

+0

如何将您的班级更改为'私人班级BSTSetIterator implements Iterator ' – gtgaxiola

回答

2
BSTSetIterator(); 

这不起作用,因为您的构造函数需要一个根,并且您没有传递该参数。如果你有一个叫做“树”一BSTSet对象,你要创建一个新的迭代器,那么你应该创建一个迭代是这样的:

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

但是,你没有一个getter在BSTSet类你的根是私人的。别担心,该问题的解决方案是创建一个公共的getter你BSTSetIterator类里,像这样:

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

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

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

相反,写你的construtor这样:

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

而且,这个定义是不正确的,因为根本是遥不可及:

private BSTNode current = root; 

你应该有这个代替:

private BSTNode current; 

至于你的其他问题,

BSTNode next = null; 

意味着你的变量称为 '下一个' 是BSTNode类型。

public E next() 

意味着您的next方法是E型。由于E和BSTNode不一样,您的退货:

return next; 

不正确。我可以给你更多的帮助,但是我意识到你现在正在学习语言,最好让你自己探索一下技术和编程,因为这样你会变得更快。 “给一个人一条鱼,然后你喂他一天,教一个人如何去钓鱼,并且你一辈子喂他。”