这是我的树节点类:
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)中都给了我stackoverflowerror。
谁能告诉我为什么他们无限循环?
谢谢。
最佳答案
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类,而不是通用对象g。因此,您一直在递归地循环遍历同一列表,而无需从第一个索引继续进行。我还将您的for循环更改为for循环,因为它更易于查看和调试。
除此之外,这给了我3根到叶的长度,我认为是正确的。
关于java - java n元树深度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29242174/