递归练习-树形结构递归获取chids和pids

for (Tree<String> tree : trees) {
    if (null != tree.getChildren()){
        chids(tree.getChildren());
        pids(tree);
    }
}
/**
     * 获取节点所有子节点
     * @param children
     */
    public void chids(List<Tree<String>> children){
        for (Tree<String> child : children) {
            HashSet<String> childrenIds = new HashSet<>();
            if (null != child.getChildren()){
                getChildrenIds(child.getChildren(),childrenIds);
                child.put("childrenIds",childrenIds);
                chids(child.getChildren());
            }
        }
    }

    public void getChildrenIds(List<Tree<String>> children, HashSet<String> chids){
        for (Tree<String> child : children) {
            chids.add(child.getId());
            if (child.getChildren() != null){
                getChildrenIds(child.getChildren(),chids);
            }
        }
    }
/**
     * 获取节点所有父节点
     * @param tree
     */
    public void pids(Tree<String> tree){
        HashSet<String> pids = new HashSet<>();
        pids.add(tree.getParentId());
        tree.put("parentsIds",pids);

        if (tree.getChildren() != null){
            for (Tree<String> child : tree.getChildren()) {
                HashSet a = new HashSet();
                a.addAll(pids);
                a.add(child.getParentId());
                child.put("parentsIds",a);
                if (null != child.getChildren()){
                    getParentIds(child.getChildren(),a);
                }
            }
        }
    }

    public void getParentIds(List<Tree<String>> children, HashSet<String> pids){
        for (Tree<String> child : children) {
            HashSet a = new HashSet();
            a.addAll(pids);
            a.add(child.getParentId());
            child.put("parentsIds",a);
            if (child.getChildren() != null){
                getParentIds(child.getChildren(),a);
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值