java递归实现树结构

package com.yan.entity;

import java.util.List;
//实体对象
public class SoftwareTree {
    private Integer id;
    private String name;
    private Integer pid;
    private List<SoftwareTree> children;
}
package com.yan.utils;

import java.util.ArrayList;
import java.util.List;

import com.yan.entity.SoftwareTree;
//递归树封装
public class MenuTree {
    private List<SoftwareTree> SoftwareTreeList = new ArrayList<SoftwareTree>();
    public MenuTree(List<SoftwareTree> SoftwareTreeList) {
        this.SoftwareTreeList=SoftwareTreeList;
    }

    //建立树形结构
    public List<SoftwareTree> builTree(){
        List<SoftwareTree> treeSoftwareTrees =new  ArrayList<SoftwareTree>();
        for(SoftwareTree SoftwareTreeNode : getRootNode()) {
            SoftwareTreeNode=buildChilTree(SoftwareTreeNode);
            treeSoftwareTrees.add(SoftwareTreeNode);
        }
        return treeSoftwareTrees;
    }

    //递归,建立子树形结构
    private SoftwareTree buildChilTree(SoftwareTree pNode){
        List<SoftwareTree> chilSoftwareTrees =new  ArrayList<SoftwareTree>();
        for(SoftwareTree SoftwareTreeNode : SoftwareTreeList) {
            if(SoftwareTreeNode.getPid() == pNode.getId()) {
                chilSoftwareTrees.add(buildChilTree(SoftwareTreeNode));
            }
        }
        pNode.setChildren(chilSoftwareTrees);
        return pNode;
    }

    //获取根节点
    private List<SoftwareTree> getRootNode() {
        List<SoftwareTree> rootSoftwareTreeLists =new  ArrayList<SoftwareTree>();
        for(SoftwareTree SoftwareTreeNode : SoftwareTreeList) {
            if(SoftwareTreeNode.getPid() == 0) {
                rootSoftwareTreeLists.add(SoftwareTreeNode);
            }
        }
        return rootSoftwareTreeLists;
    }
}

//调用
public List<SoftwareTree> getTree(SoftwareTree s) throws ParseException{
		List<SoftwareTree> list = borrowingDao.getByPage(s);

		 MenuTree menuTree =new MenuTree(list);
		 List<SoftwareTree> builTree = menuTree.builTree();
		 
		return builTree;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值