Cool
Cool
Published on 2022-03-14 / 23 Visits
0
0

Java 递归自下而上 返回父所有树节点

 public static void main(String[] args) {
        class Atree{
            String id;
            String parentId;
        }
        List<Atree> thisChildFathers =new ArrayList<>();//这个是待添加的数据,所有的数据会被添加进去,并且反馈在里面
        String id="a1";
        List<Atree> allAtresList=new ArrayList<>();//这里是用来递归的列表 ,包含所有数据,这里new 出来只是为了编译通过
        recurAtree(id, petTypes,petTypesParents);
    }
    /**
     * 递归获取父类型
     * @param petType
     * @param petTypes
     */
    private void recurAtree(String id, List<Atree> allAtresList, List<Atree> thisChildFathers) {
        for (Atree atree : allAtresList) {
            if (id.equals(atree.getId)){
                thisChildFathers.add(atree);//添加自身 因为这个参数是 引用的地址类型,被添加的数据不会丢失
                //接下来找到他的父节点
                if (atree.getParentId!=null){
                    //开始递归
                    recurAtree(atree.getParentId,allAtresList,thisChildFathers);
                }
            }
        }
    }

Comment