生成树的另一种方式

生成树有许多种方式,本文列出其中的一种。

数据库结构是

ID, PARENT形式,其中PARENT引用自己表的主键ID。根节点的parent是空。

public List<TreeNode> getTypeTree(){
List<GzdType> gTypes = gzdTypeDao.getTypes(null);
List<TreeNode> tree = new LinkedList<TreeNode>();
if (gTypes != null) {
tree = creatTree(gTypes, null);
}
return tree;
}

private List<TreeNode> creatTree(List<GzdType> gTypes,String parent){
List<TreeNode> tree = new LinkedList<TreeNode>();
for (int i = 0; i < gTypes.size(); i++) {
GzdType type = gTypes.get(i);
if (parent == null) {
if (type.getGparent() == null || type.getGparent().isEmpty()) {
TreeNode node = new TreeNode();
node.setId(type.getId());
node.setText(type.getGname());
node.setParentId(parent);
List<TreeNode> children = creatTree(gTypes, type.getId());
if (children == null || children.size() == 0) {
node.setChildren(null);
}else {
node.setChildren(children);
}
tree.add(node);
}
}else if (parent.equals(type.getGparent())) {
TreeNode node = new TreeNode();
node.setId(type.getId());
node.setText(type.getGname());
node.setParentId(parent);
List<TreeNode> children = creatTree(gTypes, type.getId());
if (children == null || children.size() == 0) {
node.setChildren(null);
}else {
node.setChildren(children);
}
tree.add(node);
}
}
return tree;
}

This entry was posted in Java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s