Java递归树形结构

private List<ZcprojectFieldDto> buildGeneralTree(List<ZcprojectFieldDto> list) {
        List<ZcprojectFieldDto> result = new ArrayList<>();
        //1. 构建一级节点
        for (ZcprojectFieldDto zcprojectFieldDto : list) {
            if (zcprojectFieldDto.getPId().equals("0")) {
                result.add(zcprojectFieldDto);
            }
        }
 
        // 2、递归获取子节点
        for (ZcprojectFieldDto parent : result) {
            parent = recursiveTree(parent, list);
        }
        return result;
    }
 
    /**
     * 递归
     *
     * @return
     */
    private ZcprojectFieldDto recursiveTree(ZcprojectFieldDto parent, List<ZcprojectFieldDto> list) {
        for (ZcprojectFieldDto zcprojectFieldDto : list) {
            if (Objects.equals(parent.getId(), zcprojectFieldDto.getPId())) {
                zcprojectFieldDto = recursiveTree(zcprojectFieldDto, list);
                parent.getChildren().add(zcprojectFieldDto);
            }
        }
        return parent;
    }
posted @ 2021-12-23 11:48  Aoul  阅读(1546)  评论(0编辑  收藏  举报