JAVA后端生成树算法,从指定的叶子节点到树根生成树,从树根到所有叶子结点

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); // 这种实现慢一些
        }
       
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值