【发布时间】:2016-04-10 02:54:11
【问题描述】:
我有一个名为 Tree 的超类和一个名为 AVLTree 的子类,它扩展了 Tree 类。
一棵树的子节点也是 Tree 类型。 AVLTree 的子节点是 AVLTree。我想使用我在 Tree 类上编写的方法,在这种情况下 getLeft(返回左子)和 setLeft(设置左子)。
问题是编译器无法将 Tree 转换为 AVLTree,即使它们具有相同的变量、结构和构造函数。
关于我应该如何解决这个问题的任何想法?还是我应该只编写 AVLTree 在 Tree 类上的所有方法?
代码:
Tree.java:
public class Tree<T extends Tree<T>> {
private T left = null;
private T right = null;
private Object data = null;
public Tree () {
//nothing
}
public Tree (Object data, T left, T right) {
this.data = data;
this.left = left;
this.right = right;
}
public Tree (Object data) {
this.data = data;
}
//Get Values
public T getLeft() {
return this.left;
}
public T getRight() {
return this.right;
}
public Object getData() {
return this.data;
}
//Set Values
public void setLeft(T left) {
this.left = left;
}
public void setRight(T right) {
this.right = right;
}
public void setData(Object data) {
this.data = data;
}
public T treeFromText(String in) {
if (in=="()") return null;
int i=0;
T result = null;
//Find expression
int d = in.indexOf('c')+1;
if (d==0) return null;
int begl, endl, begr, endr;
begl = d+1;
endl = ClosingParentesis(in,begl);
endr = in.length()-2;
begr = OpeningParentesis(in,endr);
T left = null, right = null;
if (begl-endl==0) {
left = null;
} else left = treeFromText(in.substring(begl,endl+1));
if (begr-endr==0) {
right = null;
} else right = treeFromText(in.substring(begr,endr+1));
result.setData(in.charAt(d));
result.setLeft(left);
result.setRight(right);
return result;
}
public static int ClosingParentesis(String in, int openPos) {
int closePos = openPos;
int counter = 1;
while (counter > 0 && closePos < in.length()-1) {
closePos++;
if (in.charAt(closePos)=='(') counter++;
if (in.charAt(closePos)==')') counter--;
}
return closePos;
}
public static int OpeningParentesis(String in, int closePos) {
int openPos = closePos;
int counter = 1;
while (counter > 0 && openPos > 0) {
openPos--;
if (in.charAt(openPos)=='(') counter--;
if (in.charAt(openPos)==')') counter++;
}
return openPos;
}
AVLTree.java:
public class AVLTree extends Tree<AVLTree> {
/*
//Values and Variables
private AVLTree left = null;
private AVLTree right = null;
private Object data;
//Inicialization
public AVLTree (Object data, AVLTree left, AVLTree right) {
super(data,left,right);
}
public AVLTree (Object data) {
super(data);
}
*/
public int getfactor() {
return getHeight(this.getLeft())-getHeight(this.getRight());
}
}
Test.java:
public static void main(String[] args) {
AVLTree tree = new AVLTree();
Scanner console = new Scanner(System.in);
String in = console.nextLine().toLowerCase();
tree = (AVLTree) tree.treeFromText(in); //The error is here.
System.out.println(tree.getHeight());
System.out.println(tree.TreePreOrder());
}
我希望它起作用的方式是,如果 Test.java 中的“in”字符串是“(c3()(c2()()))”,则返回值必须是值为 3 和右的树值为 2 的儿子。此返回必须是 Tree 类型或任何扩展 Tree 的类型。
【问题讨论】:
-
请向我们展示代码 sn-ps,以便我们确定我们理解您的要求。
-
@StephenC 刚刚添加了问题上的代码。
-
将 Tree 视为一个接口,并在基类(可能是 BaseTree)和 AVLTree 上实现它。然后只接受 Tree(接口)作为类型