生成树
树的实体类以及操作方法
public class DimTreeContent { private String nodeId; private String nodeName; private DimTreeContent parentNode; private List<DimTreeContent> childList; public DimTreeContent() { initChildList(); } public void addChildNode(DimTreeContent treeNode) { initChildList(); childList.add(treeNode); } /** * 插入节点 */ public void initChildList() { if (childList == null) childList = new ArrayList<DimTreeContent>(); } /** * 查找节点 * @param id * @return */ public DimTreeContent findTreeNodeById(String id) { if (this.nodeId == id) return this; if (childList.isEmpty() || childList == null) { return null; } else { int childNumber = childList.size(); for (int i = 0; i < childNumber; i++) { DimTreeContent child = childList.get(i); DimTreeContent resultNode = child.findTreeNodeById(id); if (resultNode != null) { return resultNode; } } return null; } } //深度遍历 public static List<String> listmaps = new ArrayList<String>(); public void traverse() { if ("".equals(nodeId) || nodeId == null) return; if (childList == null || childList.isEmpty()){ listmaps.add(this.nodeId); return; } for (int i = 0; i < childList.size(); i++) { DimTreeContent child = childList.get(i); child.traverse(); } } public List<List<Map<String,String>>> getDimContent(){ List<List<Map<String,String>>> listList = new ArrayList<List<Map<String,String>>>(); for(int i = 0; i < listmaps.size(); i++){ List<Map<String,String>> list = new ArrayList<Map<String,String>>(); DimTreeContent dimContent = findTreeNodeById(listmaps.get(i)); Map<String,String> map = new HashMap<String,String>(); map.put(dimContent.nodeId, dimContent.nodeName); list.add(map); while(dimContent.getParentNode().nodeId != "rootid"){ dimContent = dimContent.getParentNode(); Map<String,String> m = new HashMap<String,String>(); m.put(dimContent.nodeId, dimContent.nodeName); list.add(m); } listList.add(list); } return listList; } public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } public String getNodeName() { return nodeName; } public void setNodeName(String nodeName) { this.nodeName = nodeName; } public DimTreeContent getParentNode() { return parentNode; } public void setParentNode(DimTreeContent parentNode) { this.parentNode = parentNode; } public List<DimTreeContent> getChildList() { return childList; } public void setChildList(List<DimTreeContent> childList) { this.childList = childList; } }
生成树使用了栈加树实现的生成。