我创建了一个二进制搜索树,并且可以对其进行添加和删除,但是当我尝试使用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();
}
}
答案 0 :(得分:1)
此:
System.out.println("In-order: " + tree.getInorderIterator());
...打印迭代器对象本身(的字符串值)。如果要打印树元素,则必须使用迭代器来检索元素并进行打印。例如,
for (Iterator<?> it = tree.getInorderIterator(); it.hasNext();) {
System.out.println(it.next());
}