我想为BinaryTree写一个自定义的迭代器。此迭代器应返回accuracies = []
losses = []
for i in range(0, len_X // batch_size + 1:
X_batch, Y_batch = next_batch(
total=len_X,
images=X,
labels=Y,
batch_size=batch_size,
index=i
)
los, acc= sess.run([loss, accuracy])
accuracies.append(acc)
losses.append(loss)
test_acc = np.mean(accuracies)
test_loss = np.mean(losses)
个对象。在递归调用fillList的行中,文件Node<?>
中出现编译错误:InorderIterator
错误是:fillList(currentNode.getLeft());
有人可以向我解释为什么我的方法无效吗?或如何解决
Error:(14, 37) java: incompatible types: rclib.Node cannot be converted to T
Node.java
package rclib;
public class Node<T extends Comparable<T>> {
T key;
Node<T> left;
Node<T> right;
public Node(T key, Node left, Node right) {
this.key = key;
this.left = left;
this.right = right;
}
public Node(T key) {
this(key, null, null);
}
public Node<T> getLeft() {
return left;
}
public Node<T> getRight() {
return right;
}
public T getKey() {
return key;
}
}
InorderIterator.java
package rclib;
import java.util.*;
public class InorderIterator<T extends Node<?>> implements Iterator<T> {
LinkedList<T> list;
public InorderIterator(T root) {
list = new LinkedList<T>();
fillList(root);
}
public void fillList(T currentNode) {
if (currentNode == null) return;
fillList(currentNode.getLeft());
list.add(currentNode);
fillList(currentNode.getRight());
}
@Override
public boolean hasNext() {
return !list.isEmpty();
}
@Override
public T next() {
return list.removeFirst();
}
}
AVLTree.java
答案 0 :(得分:1)
您也许应该做类似的事情:
package rclib;
import java.util.*;
public class InorderIterator<T extends Comparable<T>> implements Iterator<Node<T>> {
LinkedList<Node<T>> list;
public InorderIterator(Node<T> root) {
list = new LinkedList<Node<T>>();
fillList(root);
}
public void fillList(Node<T> currentNode) {
if (currentNode == null) return;
fillList(currentNode.getLeft());
list.add(currentNode);
fillList(currentNode.getRight());
}
@Override
public boolean hasNext() {
return !list.isEmpty();
}
@Override
public Node<T> next() {
return list.removeFirst();
}
}
答案 1 :(得分:1)
您必须明确指定您使用Node
而不是? extends Node
,这可能最终不符合正确的用法。
public static class InorderIterator<T extends Comparable<T>> implements Iterator<Node<T>> {
LinkedList<Node<T>> list;
public InorderIterator(Node<T> root) {
list = new LinkedList<>();
fillList(root);
}
public void fillList(Node<T> currentNode) {
if (currentNode == null) return;
fillList(currentNode.getLeft());
list.add(currentNode);
fillList(currentNode.getRight());
}
@Override
public boolean hasNext() {
return !list.isEmpty();
}
@Override
public Node<T> next() {
return list.removeFirst();
}
}