当前位置 : 主页 > 编程语言 > c++ >

TreeHelper

来源:互联网 收集:自由互联 发布时间:2021-07-03
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.
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.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); } } }
         
        
       
      
     
    
   
  
 
网友评论