TreeHelper package com.test.helper;import com.test.exception.InternalException;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.lang.reflect.Field;import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.
package com.test.helper; import com.test.exception.InternalException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * tree generate helper */ public final class TreeHelper { private static final Logger LOGGER = LoggerFactory.getLogger(TreeHelper.class); private TreeHelper() { } /** * 生成树方法 * 将子节点放入父节点的children * * @param nodeMap * @param*/ public static void generateTree(Map nodeMap) { // 建立父子关系 for (TreeNode node : nodeMap.values()) { // 是否是根节点 if (node.checkIsRootNode()) { continue; } String parentId = node.getParentId(); if (nodeMap.containsKey(parentId)) { TreeNode parentNode = nodeMap.get(parentId); if (parentNode == null) { throw new InternalException("生成树失败"); } else { // 建立父子关系 parentNode.establishPaternity(node); } } } // sort for (T t : nodeMap.values()) { List children = t.getChildren(); if (children != null && children.size() > 0) { // 子类去实现各自的排序规则 t.sortChildren(children); } } } /** * 树的深度遍历 * * @param root * @param * @return */ public static List getListFromTree(T root) { List list = new ArrayList<>(); if (root == null) { return list; } depthFirstSearch(root, list); return list; } private static void depthFirstSearch(T node, List list) { list.add(node); for (Object child : node.getChildren()) { depthFirstSearch((T) child, list); } } }