【发布时间】:2019-04-21 19:18:08
【问题描述】:
我创建了一个二叉搜索树,我可以添加和删除它,但是当我尝试使用 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();
}
}
【问题讨论】:
-
您正在打印迭代器对象本身。如果要打印树的每个元素,则需要在循环中使用迭代器,并打印它返回的每个元素。
标签: java iteration binary-tree binary-search-tree inorder