java学习-无限层级递归的思想

一.贴一个不久之前学到的递归方法

1.1.严格定义递归函数作用,包括参数,返回值,side-effect

1.2.先一般,后特殊

1.3.每次调用,必须缩小问题规模。

1.4.每次缩小的规模范围必须为1

二 。贴一个简单的递归函数:

public class Node {
    private final int value;
    private Node next;
    public Node(int value){
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }

   public static void printLinkedList(Node head){  //用于打印输出值
        while (head != null){
            System.out.print(head.getValue());
            System.out.print(" ");
            head = head.getNext();
        }
       System.out.println();
   }
}

  实现类:

public class LinkedListCreator {
    //开始
    public Node createLinkedListFirst(List<Integer> data){
        Node firstNode = new Node(data.get(0));  //新建一个对象,赋予新值 由于Node 类定义的值是 final 保证不会被修改
        Node seondOfNode = createLinkedList(data.subList(1,data.size())); //而不是  Node secondNode = new Node(data.get(1))
        firstNode.setNext(seondOfNode);
        return firstNode;
    }

    //最后的结果
    public Node createLinkedList(List<Integer> data){
        if (data.isEmpty()){
            return null;
        }
        Node firstNode = new Node(data.get(0));
        Node headOfNode = createLinkedList(data.subList(1,data.size()));
        firstNode.setNext(headOfNode);
        return firstNode;
    }

    public static void main(String[] args) {
        LinkedListCreator linkedListCreator = new LinkedListCreator();

        Node.printLinkedList(new LinkedListCreator().createLinkedList(Arrays.asList(1,2)));
        Node.printLinkedList(linkedListCreator.createLinkedList(new ArrayList<Integer>()));


        Node.printLinkedList(linkedListCreator.createLinkedList(Arrays.asList(1)));
        Node.printLinkedList(linkedListCreator.createLinkedList(Arrays.asList(1,2,3,4,5)));
    }
}

三结合实际使用:

首先。得得到一个,根节点。从根节点再去找寻子节点,使用Set集合 排重复值

也就是说,再一次调用此函数时,子节点变为父节点,直到查询到无子节点。

    private Set<Category>  findChildCategory(Set<Category> categorySet,Integer categoryId){
        Category category = categoryMapper.selectByPrimaryKey(categoryId);
        if (category != null){
        
             categorySet.add(category);
        }
        List<Category> categoryList = categoryMapper.selectcategoryChildrenByParentId(categoryId);
        for (Category categoryItem : categoryList){
            findChildCategory(categorySet,categoryItem.getId());  //categorySet 值叠加,
        }
        return categorySet;
    }
发布了37 篇原创文章 · 获赞 4 · 访问量 6836

猜你喜欢

转载自blog.csdn.net/m0_37918421/article/details/88854241