数据库中利用ParentId实现树状列表,如果查询出先根(根左右)遍历的列表,可以用本文介绍的方法构造出树结构。
List<OrganizationInfo> list= #查询出先根列表# OrganizationTree tree= new OrganizationTree(); buildOrganTree(list,tree); return tree;
其中OrganizationInfo为结点类型,其中有指示父节点的属性。
需要构建的树:
public class OrganizationTree implements Serializable{ private OrganizationInfo node; private List<OrganizationTree> childNodes; }
实现过程:
private void buildOrganTree(List<OrganizationInfo> list,OrganizationTree tree) { Stack<OrganizationTree> st = new Stack<OrganizationTree>(); if(list.size()<=0) return; OrganizationInfo curNode = list.get(0); tree.setNode(curNode); OrganizationTree pNode = tree; OrganizationTree preNode = tree; for(int i=1;i<list.size();i++){ OrganizationTree snode = new OrganizationTree(); snode.setNode(list.get(i)); if( list.get(i).getParentId().equals(pNode.getNode().getOrganizationId()) ){ if(pNode.getChildNodes()==null){ List<OrganizationTree> child = new ArrayList<OrganizationTree>(); child.add(snode); pNode.setChildNodes(child); } else{ pNode.getChildNodes().add(snode); } } else{ if( list.get(i).getParentId().equals(list.get(i-1).getOrganizationId())) { st.push(pNode); pNode = preNode; if(pNode.getChildNodes()==null){ List<OrganizationTree> child = new ArrayList<OrganizationTree>(); child.add(snode); pNode.setChildNodes(child); } else{ pNode.getChildNodes().add(snode); } } else{ do{ pNode =st.pop(); }while( !list.get(i).getParentId().equals(pNode.getNode().getOrganizationId()) ); pNode.getChildNodes().add(snode); } } preNode =snode; } }