我实现了一个通用的二叉搜索树类,它有一个嵌套的节点类,如下所示:
public class BST<E extends Comparable<E>> implements Iterable<E> {
protected class Node {
E data;
Node leftChild;
Node rightChild;
int depth;
public Node(E data) {
this.data = data;
this.leftChild = null;
this.rightChild = null;
this.depth = 0;
}
public int getDepth(){
return this.depth;
}
public void setDepth(int depth){
this.depth = depth;
}
}
protected Node root;
//methods are implemented past this point
我还有一个存储生命点和标签(只是一个字母)的 MazeNode 对象类:
public class MazeNode implements Comparable<MazeNode>{
private String label; // label of the node
private int lifePoints; // number of possible life points our hero can collect at this maze node
public MazeNode(String label, int lifePoints) {
this.label = label;
this.lifePoints = lifePoints;
}
public String getLabel() {
return label;
}
public int getLifePoints() {
return lifePoints;
}
@Override
public int compareTo(MazeNode o) {
return this.getLabel().compareTo(o.getLabel());
}
@Override
public String toString(){
return this.getLabel();
}
}
这是我的迷宫类,它进行迭代并找到一条向下到达叶节点的路径,我的英雄有足够的生命点可以到达叶节点:
public class Maze extends BST<MazeNode> {
private int maxDepth = 0;
public void play(Hero hero) {
Iterator<MazeNode> pre1 = this.preOrderIterator();
Iterator<MazeNode> pre2 = this.preOrderIterator();
int maxDepth = 0;
while (pre1.hasNext()) {
MazeNode node = pre1.next();
if (node.leftChild == null && node.rightChild == null) {
int x = node.getDepth();
if (maxDepth < x) {
maxDepth = x;
}
}
Stack<MazeNode> stack = new Stack<MazeNode>();
node = pre2.next();
while (pre2.hasNext()) {
if (node.leftChild == null && node.rightChild == null) {
int y = node.getDepth();
if (y == maxDepth && hero.getLives() >= 0) {
System.out.println(stack.toArray());
while (node != stack.peek().leftChild || node != stack.peek().rightChild) {
stack.pop();
hero.editLife(-(node.getLifePoints()));
}
} else if (y < maxDepth) {
while (node != stack.peek().leftChild || node != stack.peek().rightChild) {
stack.pop();
hero.editLife(-(node.getLifePoints()));
}
}
} else {
stack.push(node);
hero.editLife(node.getLifePoints());
}
node = pre2.next();
}
}
}
} 该项目的目标是,给定一个带有标签和每个节点 lifePoints 的 BST,找到我的英雄可以从最高深度节点退出的所有路径,但我的英雄只有在他有足够的生命点才能到达时才能退出底部。
我的 play() 方法中的问题是我的节点变量是 MazeNode 类型,因此无法访问我的 BST 节点类中的 leftChild、rightChild 和深度字段。我怎样才能做到呢?我只是为了上下文写出逻辑,但显然它不起作用,因为我的节点变量无法访问上述数据。 我必须保留节点类型的 BST 节点类,我不能使它通用。我也无法创建一个新课程来尝试将它们放在一起。
我已经尝试过类型转换,但我对泛型还是陌生的,所以我还没有真正弄明白。正如我提到的,我不允许创建新类或将我的 BST 节点更改为通用类型。