gpt4 book ai didi

java - BST 的迭代方法

转载 作者:行者123 更新时间:2023-12-02 07:32:02 44 4
gpt4 key购买 nike

这些是我的领域:

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?

最佳答案

BSTSetIterator();

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

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

但是,您的 BSTSet 类中没有 getter,并且您的根是私有(private)的。别担心,这个问题的解决方案是在 BSTSetIterator 类中创建一个公共(public) getter,如下所示:

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

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

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

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

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

此外,这个定义是不正确的,因为 root 无法访问:

private BSTNode current = root;

你应该用这个:

private BSTNode current;

至于你的其他问题,

BSTNode next = null;

表示名为“next”的变量是 BSTNode 类型。

public E next()

意味着你调用的 next 方法是 E 类型。由于E和BSTNode不一样,你的返回:

return next;

不正确。我可以给你更多的帮助,但我意识到你现在正在学习这门语言,最好让你自己探索一般的技术和编程,因为这样你会变得更快。 “授人以鱼,可食一日;授人以渔,可食一生。”

关于java - BST 的迭代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12790261/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com