当前位置:   article > 正文

Java中使用递归算法实现查找树形结构中所有父级和子级节点_java 树型结构筛选父级id

java 树型结构筛选父级id

场景

在企业架构管理中使用树形结构进行管理,如图:

注:如果A的id是B的pid,那么A就是B的父级。

数据库数据如下:

现在需要根据传递的id查询此节点所有的父级节点以及此节点所有的子级节点。

实现

递归查询父级节点

1.一个节点只能有一个父级节点。

2.首先根据参数传递的id属性查询到pid为这个id的对象a,然后再获取这个刚查询的对象a的id,再查询pid为对象a的id的对象b,以此类推。

  1. List<Long> result1 = new ArrayList<Long>();
  2.  public void selectFather(Long id){
  3.             //查询数据库中对应id的实体类
  4.             SysEnterpriseOrg sysEnterpriseOrg = sysEnterpriseOrgMapper.selectById(id);
  5.             //查询父级架构
  6.             //此处使用mybaatisPlus的条件构造器,查询id等于pid的对象
  7.             QueryWrapper<SysEnterpriseOrg> sysEnterpriseOrgChildQueryWrapper = new QueryWrapper<SysEnterpriseOrg>();
  8.             sysEnterpriseOrgChildQueryWrapper.eq("id",sysEnterpriseOrg.getPid());
  9.             //查询出符合条件的对象
  10.             sysEnterpriseOrg= sysEnterpriseOrgMapper.selectOne(sysEnterpriseOrgChildQueryWrapper);
  11.             if(sysEnterpriseOrg!=null){
  12.                 //如果查出的对象不为空,则将此对象的id存到全局变量中,并且继续调用自己,即递归,一直到查询不到为止
  13.                 result1.add(sysEnterpriseOrg.getId());
  14.                 selectFather(sysEnterpriseOrg.getId());
  15.             }
  16.     }

递归查询子级节点

1.一个节点可能有多个子级节点,每个自己节点可能还有更多的子级节点。

2.所以递归时的参数用一个list来接受,首先遍历参数list,分别查询pid为参数id的对象。

3.每一个参数id所查询返回的数据是一个对象的list。

4.遍历list获取符合条件的对象的id值,一份存到temp中用作递归的参数,并存到全局变量中用来获取所有符合条件的id。

  1. List<Long> result = new ArrayList<Long>();
  2. public void selectChild(List<Long> ids){
  3.         //用来存取调用自身递归时的参数
  4.         List<Long> temp= new ArrayList<Long>();
  5.         //查询数据库中对应id的实体类
  6.         List<SysEnterpriseOrg> sysEnterpriseOrgList = new ArrayList<SysEnterpriseOrg>();
  7.         //遍历传递过来的参数ids
  8.         for (Long id :ids) {
  9.             //查询子级架构
  10.             //此处使用mybaatisPlus的条件构造器,查询pid等于id的对象
  11.             QueryWrapper<SysEnterpriseOrg> sysEnterpriseOrgChildQueryWrapper = new QueryWrapper<SysEnterpriseOrg>();
  12.             sysEnterpriseOrgChildQueryWrapper.eq("pid",id.toString());
  13.             //查询结果返回一个list
  14.             sysEnterpriseOrgList= sysEnterpriseOrgMapper.selectList(sysEnterpriseOrgChildQueryWrapper);
  15.             //遍历list获取符合条件的对象的id值,一份存到temp中用作递归的参数,并存到全局变量中用来获取所有符合条件的id
  16.             for (SysEnterpriseOrg s:sysEnterpriseOrgList) {
  17.                 temp.add(s.getId());
  18.                 result.add(s.getId());
  19.             }
  20.         }
  21.         if(temp.size()!=0&&temp!=null){
  22.             selectChild(temp);
  23.         }
  24.     }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/77376?site
推荐阅读
相关标签
  

闽ICP备14008679号