4/11 10:20 更新了一些算法解释
4/18 17:17 更新了生成子树的方法,更加灵活了
先贴代码吧
import java.util.*;
/**
* @Author xjd
* @Date 2019/4/3 10:30
* @Version 1.0
*/
public class GeTreeUtil {
/**
* 传入的节点结构必须继承本工具支持的数据结构
* @author xjd
* @date 2019/4/10 17:20
*/
public static class BaseTreeNode{
protected Long id;
protected Long pid;
protected Boolean leafNode;
protected List<BaseTreeNode> childList;
protected BaseTreeNode(Long id, Long pid, Boolean leafNode, List<BaseTreeNode> childList) {
this.id = id;
this.pid = pid;
this.leafNode = leafNode;
this.childList = childList;
}
}
/**
* 根据叶子节点生成只包含叶子节点分支的树,可以是深林,最终汇成一棵树
* @param allNodeList 整棵树或者整个深林的所有的节点
* @param leafNodeList 需要展示的叶子节点
* @return 分支树
*/
public static List<? extends BaseTreeNode> getBranchTree(List<? extends BaseTreeNode> allNodeList, List<? extends BaseTreeNode> leafNodeList){
Hashtable<Long, List<BaseTreeNode>> dicNode = new Hashtable<>();
for (BaseTreeNode baseTreeNode : leafNodeList) {
List<BaseTreeNode> childList = dicNode.get(baseTreeNode.pid);
if(null == childList){
childList = new ArrayList<>();
dicNode.put(baseTreeNode.pid, childList);
}
childList.add(baseTreeNode);
}
/* Map<Long, BaseTreeNode> allNodeMap = new HashMap<>();
for (BaseTreeNode node : allNodeList) {
allNodeMap.put(node.id, node);
}*/
if(dicNode.isEmpty()){
return Collections.emptyList();
}
while (!(dicNode.containsKey(-1L) && dicNode.size() == 1)){ // 递归出口
ConbineDirectParant(allNodeList, dicNode);
// dicNode = ConbineDirectParant(allNodeMap, dicNode); // 这种实现慢一些
}