这是我的树节点类:
public class Generalization extends Class_object {
private List<Generalization> superClasses;
private List<Generalization> subClasses;
public boolean isRoot() {
return superClasses.size() == 0;
}
public boolean isLeaf() {
return subClasses.size() == 0;
}
// path length to root
public String getDIT() {
return Integer.toString(recuDIT(this));
}
public int recuDIT(Generalization g) {
if (g.isRoot())
return 0;
else {
int maxLength = 0;
for (Generalization gen : superClasses) {
maxLength = Math.max(maxLength, recuDIT(gen));
}
return maxLength + 1;
}
}
// path length to leaf
public String getCLD() {
return Integer.toString(recuCLD(this));
}
public int recuCLD(Generalization g) {
if (g.isLeaf())
return 0;
else {
int maxLength = 0;
for (Generalization gen : subClasses) {
maxLength = Math.max(maxLength, recuCLD(gen));
}
return maxLength + 1;
}
}
}
每个节点都有其父节点和子节点。但是当我执行程序时,它会在递归函数(CLD和DIT)中给出 stackoverflower 。 谁能告诉我为什么他们无限循环? 感谢。
答案 0 :(得分:1)
public class Generalization {
private List<Generalization> superClasses;
private List<Generalization> subClasses;
public Generalization(){
superClasses = new ArrayList<Generalization>();
subClasses = new ArrayList<Generalization>();
}
public boolean isRoot() {
return superClasses.size() == 0;
}
public boolean isLeaf() {
return subClasses.size() == 0;
}
// path length to root
public String getDIT() {
return Integer.toString(recuDIT(this));
}
public int recuDIT(Generalization g) {
if (g.isRoot())
return 0;
else {
int maxLength = 0;
for(int i = 0 ; i < g.superClasses.size(); i++){
maxLength = Math.max(maxLength, recuDIT(g.superClasses.get(i)));
}
return maxLength + 1;
}
}
// path length to leaf
public String getCLD() {
return Integer.toString(recuCLD(this));
}
public int recuCLD(Generalization g) {
if (g.isLeaf())
return 0;
else {
int maxLength = 0;
for(int i = 0 ; i < g.subClasses.size(); i++){
maxLength = Math.max(maxLength, recuCLD(g.subClasses.get(i)));
}
return maxLength + 1;
}
}
public static void main(String[] args){
Generalization root = new Generalization();
Generalization ch1 = new Generalization();
Generalization ch2 = new Generalization();
root.subClasses.add(ch1);
root.subClasses.add(ch2);
Generalization gc1 = new Generalization();
Generalization gc2 = new Generalization();
Generalization gc3 = new Generalization();
ch2.superClasses.add(root);
ch2.subClasses.add(gc1);
ch2.subClasses.add(gc2);
ch1.subClasses.add(gc3);
ch1.superClasses.add(root);
Generalization ggc1 = new Generalization();
gc3.subClasses.add(ggc1);
gc3.superClasses.add(ch1);
gc2.superClasses.add(ch2);
gc1.superClasses.add(ch2);
ggc1.superClasses.add(gc3);
System.out.println(ggc1.getDIT());
System.out.println(root.getCLD());
}
}
如果我不知道我是否正确设置树或真正测试那么多,这对我有用。主要问题是您使用的是类recuDIT / CLD而不是方法中的Generalization对象g。所以你不断地循环遍历同一个列表,而不是从第一个索引转移。我还将每个循环更改为for循环,因为我更容易查看和调试。
除此之外,这给了我3根长度到根和长度到叶子,我认为是正确的。