尝试使用 getInorderIterator 但它不打印我的树 InOrder
Trying to use getInorderIterator but its not printing my tree InOrder
我创建了一个二叉搜索树,我可以添加和删除它,但是当我尝试使用 getInorderIterator 方法并打印树时,它会打印 "TreePackage.BinaryTree$InorderIterator@2e817b38"
也许我只是调用方法错误?
这就是我在主页面中打印它的方式 class:
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());
}
我创建了一个二叉搜索树,我可以添加和删除它,但是当我尝试使用 getInorderIterator 方法并打印树时,它会打印 "TreePackage.BinaryTree$InorderIterator@2e817b38"
也许我只是调用方法错误?
这就是我在主页面中打印它的方式 class:
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());
}