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

问题描述 投票:2回答:1

我创建了一个二叉搜索树,我可以添加和删除它,但当我尝试使用getInorderIterator方法并打印树时,它打印“Tree Package.Binary Tree $ Inorder Iterator @ 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
1个回答
1
投票

这个:

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

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

for (Iterator<?> it = tree.getInorderIterator(); it.hasNext();) {
    System.out.println(it.next());
}
© www.soinside.com 2019 - 2024. All rights reserved.