请教一个递归的问题。
public Class Category{
private String name;
private Category parent;
private List<Category> childArray;
public Category[] getPath(){
//得到包括当前类所有父类的树。从顶层类开始,到当前类。
}
}
请大侠不吝赐教,谢谢。
每个类都只有一个父类。 在线等。
------解决方案--------------------
层级数不太多的话,直接递归。。
public Category[] getPath() {
return this._getPath(1);
}
private Category[] _getPath(int level) {
Category[] path;
if (parent == null) {
path = new Category[level];
} else {
path = this.parent._getPath(level + 1);
}
path[path.length - level] = this;
return path;
}
------解决方案--------------------
或者不用递归,用个List先存着也行
public Category[] getPath() {
List<Category> list = new LinkedList<>();
Category category = this;
while (category != null) {
list.add(0, category);
category = category.parent;
}
Category[] path = new Category[list.size()];
int i = 0;
for (Category item : list) {
path[i++] = item;
}
return path;
}