【发布时间】:2015-07-28 10:42:58
【问题描述】:
我有一个数据库表,其中包含StructureGuid 和ParentGuid 的记录。所以大多数父母都有孩子。
我想创建一个递归算法来构建树。
树的类是Header.java:
public class Header implements MultiLevelExpIndListAdapter.ExpIndData {
private List<Header> mChildren;
private boolean mIsGroup;
private int mGroupSize;
public String header;
public String structureGuid;
public Header(String header, String guid){
this.header = header;
this.structureGuid = guid;
mChildren = new ArrayList<Header>();
setIndentation(0);
}
@Override public List<? extends MultiLevelExpIndListAdapter.ExpIndData> getChildren() {
return mChildren;
}
@Override public boolean isGroup() {
return mIsGroup;
}
@Override public void setIsGroup(boolean b) {
mIsGroup = b;
}
@Override public void setGroupSize(int i) {
mGroupSize = i;
}
public int getGroupSize() {
return mGroupSize;
}
public void addChild(Header child){
mChildren.add(child);
child.setIndentation(getIndentation() + 1);
}
}
我使用 SQL 框架来获取根节点,然后循环遍历它们。停止情况是节点 (Header) 没有任何子节点。
代码:
//Get the root nodes
public static List<Header> getHeaders(){
List<Structure> list = new Select().from(Structure.class)
.where(Condition.column(Structure$Table.PARENTGUID).eq(""))
.and(Condition.column(Structure$Table.STATUS).eq(true))
.and(Condition.column(Structure$Table.REQUIRED).eq(true))
.orderBy("Sequence ASC").queryList();
ArrayList<Header> headers = new ArrayList<>();
for (Structure struct: list){
headers.add(new Header(struct.getDescription(), struct.StructureGUID));
}
return addChildren(list, headers);
}
//recursively return child nodes
public static List<Header> addChildren(List<Structure> structures, List<Header> headers){
List<Header> newHeader = new ArrayList<>();
//recurring algorithm - while there are no kids get headers
if(headers.size() > 0) {
for (int i = 0; i < headers.size(); i++) {
//get children of that header - if none return empty arraylist
//else loop through and addChildren
List<Structure> list = new Select().from(Structure.class)
.where(Condition.column(Structure$Table.PARENTGUID).eq(headers.get(i).structureGuid))
.and(Condition.column(Structure$Table.STATUS).eq(true))
.and(Condition.column(Structure$Table.REQUIRED).eq(true))
.orderBy("Sequence ASC").queryList();
List <Header> temp = new ArrayList<Header>();
Log.e("TAG", "size of array: " + list.size());
if (list.size() != 0) {
for (Structure struct : list) {
headers.get(i).addChild(new Header(struct.getDescription(), struct.StructureGUID));
temp.add(headers.get(i));
}
}
newHeader = addChildren(list, temp);
}
}
return newHeader;
}
现在它卡在第一个根节点的第一个子节点的连续循环中。
【问题讨论】:
-
为什么要递归?你没有来自 SQL 的记录集吗?如果您已经知道哪个孩子属于父母,则获取父母并附加孩子。
-
@fantaghirocco 你看它就像一棵结构树,所以一个元素的子元素有自己的子元素。我必须事先知道树的长度,如果我不想重复,那也是更多不必要的代码。