gpt4 book ai didi

java - 尝试使用 getInorderIterator 但它不打印我的树 InOrder

转载 作者:行者123 更新时间:2023-11-30 10:04:38 25 4
gpt4 key购买 nike

我创建了一个二叉搜索树,我可以添加和删除它,但是当我尝试使用 getInorderIterator 方法并打印树时,它会打印“TreePackage.BinaryTree$InorderIterator@2e817b38”

也许我只是以错误的方式调用了方法?

这就是我在主类中打印它的方式:

System.out.println("In-order: " + tree.getInorderIterator());

这是我对 getInorderIterator() 的实现:

 public Iterator<T> getInorderIterator()
{
return new InorderIterator();
}

private class InorderIterator implements Iterator<T>
{
private StackInterface<BinaryNode<T>> nodeStack;
private BinaryNode<T> currentNode;

public InorderIterator()
{
nodeStack = new LinkedStack<>();
currentNode = root;
}

public boolean hasNext()
{
return !nodeStack.isEmpty() || (currentNode != null);
}

public T next() {
BinaryNode<T> nextNode = null;

while (currentNode != null) {
nodeStack.push(currentNode);
currentNode = currentNode.getLeftChild();
}
if (!nodeStack.isEmpty()) {
nextNode = nodeStack.pop();
assert nextNode != null;

currentNode = nextNode.getRightChild();
} else
throw new NoSuchElementException();

return nextNode.getData();
}
public void remove()
{
throw new UnsupportedOperationException();
}
}

最佳答案

这个:

System.out.println("In-order: " + tree.getInorderIterator());

... 打印迭代器对象本身的(字符串值)。如果要打印树元素,则必须使用迭代器检索元素并打印它们。例如,

for (Iterator<?> it = tree.getInorderIterator(); it.hasNext();) {
System.out.println(it.next());
}

关于java - 尝试使用 getInorderIterator 但它不打印我的树 InOrder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55785928/

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