构建一个Node树

方便遍历查找数据,比如存储机构人员数据。

建立 Node 对象

public class Node implements java.io.Serializable{
    private int id;

    private int parentId; // 父节点的ID

    private Node parent; // 父节点

    private List<Node> children; // 子节点集合

    private int level; // 树的层级

    private int sort; 

    private int rootId; // 根节点的ID

    private String type; // 节点类型

    private boolean isLeaf; // 是否是叶子节点

    private String description; // 节点的描述

    // ... 其他自定义属性


    public Node() {
        super();
    }

    // 构造器...
    // set、get方法...
}

将集合建立成树结构

/**
 * 将集合建立成树结构
 *
 * @param dirs
 * @return
 */
@SuppressWarnings("unchecked")
public static List<Node> buildListToTree(List<Node> dirs) {
    List<Node> roots = findRoots(dirs); // 找出集合中的根元素
    List<Node> notRoots = (List<Node>) CollectionUtils.subtract(dirs, roots); // 集合相减,去除根元素的集合
    for (Node root : roots) {
        root.setChildren(findChildren(root, notRoots)); // 递归找子节点
    }
    return roots;
}

/**
 * 找出集合中的根元素
 *
 * @param
 * @return
 */
public static List<Node> findRoots(List<Node> allNodes) {
    List<Node> results = new ArrayList<Node>();
    for (Node node : allNodes) {
        boolean isRoot = true;
        for (Node comparedOne : allNodes) {
            if (node.getParentId() == comparedOne.getId()) { // 如果存在当前Node的父ID,则当前节点不是根元素,反之,则是.
                isRoot = false;
                break;
            }
        }
        if (isRoot) {
            node.setLevel(0);
            results.add(node);
            node.setRootId(node.getId());
        }
    }
    return results;
}


/**
 * 递归找子目录
 *
 * @param root
 * @param
 * @return
 */
@SuppressWarnings("unchecked")
private static List<Node> findChildren(Node root, List<Node> allNodes) {
    List<Node> children = new ArrayList<Node>();

    for (Node comparedOne : allNodes) {
        if (comparedOne.getParentId() == root.getId()) {
            comparedOne.setParent(root);
            comparedOne.setLevel(root.getLevel() + 1);
            children.add(comparedOne);
        }
    }
    List<Node> notChildren = (List<Node>) CollectionUtils.subtract(allNodes, children);
    for (Node child : children) {
        List<Node> tmpChildren = findChildren(child, notChildren); // 递归查找
        if (tmpChildren == null || tmpChildren.size() < 1) { // 没有子节点,则为叶子节点
            child.setLeaf(true);
        } else {
            child.setLeaf(false);
        }
        child.setChildren(tmpChildren);
    }
    return children;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值