Recursive algorithm based on the traffic scenario, the tree structure data, encapsulating the solution

This article Source: GitHub · Click here || GitEE · Click here

A recursive algorithm

1, the concept Introduction

The core idea of ​​recursive algorithm is the problem by repeating the same kind of way, or broken down into sub-problems, which can use a unified solution. Many programming languages ​​support method or function calls itself, simply put, is a function or method body itself can call its own method structure again.

2, the base case

Here by a recursive manner, factorial, and summation correlation logic.

public class Demo01 {
    public static void main(String[] args) {
        int result1 = factorial(5);
        System.out.println(result1);
        int result2 = sum(100) ;
        System.out.println(result2);
    }
    // 递归阶乘
    private static int factorial (int n){
        if(n <= 1){
            return n ;
        }else{
            return n*factorial(n-1);
        }
    }
    // 递归求和
    private static int sum (int f){
        if(f <= 1){
            return f ;
        }else{
            return f + sum(f-1);
        }
    }
}

3 Notes

  • Instructions

Using recursion, when to clear business logic can be decomposed into repeat the same question, and to clearly know recursive end condition, otherwise it is prone to an endless loop.

  • Describes the advantages and disadvantages

Code recursive algorithm is relatively simple, better readability; but there will be many times repeated calls in the actual business processes, if not handled properly, it is prone to error StackOverflowError.

Second, the tree

1, concept description

Tree is a hierarchical nested structure. A tree structure of the outer and inner layers have a similar structure, so the structure can be recursive multi FIG.

2, illustrations and definitions

Recursive algorithm based on the traffic scenario, the tree structure data, encapsulating the solution

  • Root

The root of the tree, there is no parent node, A node as FIG.

  • Sibling

We have children of the same parent node. B and C and D in FIG node.

  • Leaf node

No child node. Other nodes E and F in FIG.

  • Branch of

It refers to a node has several child nodes. As: A is 3, B is 2.

  • Node depth

It refers to the longest path from the node to a node. Figure A is 2, B is 1.

Third, the application scenarios

1, scene description

Based on recursive algorithm, we deal with a lot of business data in a tree structure. Common business scenario is as follows:

  • Provinces three linkage inquiry;
  • System modules, menus, buttons authorized;
  • Common business data classification: commodity classification;
  • Common industries detailed classification;

2, Special Scene

In the management system, the system modules, menus, buttons may be authorized to operate when the following situation.

Recursive algorithm based on the traffic scenario, the tree structure data, encapsulating the solution

If the system administrator authority shown in the figure, but the permissions given to the following operations personnel, and the need to 3 menu Menu No. 5 is set to the same level, this time is substantially the handling of the menu No. 3 as the parent ID 3 No root menus and functions under the authority of this place as two trees were treated separately, and finally merge data just fine. Accompanied, if necessary, in accordance with the coding node, for example NODE01, NODE0101, NODE0102 etc., here for the scene description, it is hoped in time to deal with similar business, open to ideas, not be confined to a single tree structure. 业务很多时候都是出人意料甚至是令人生厌,不过这确实就是生活.

3, the tool type of packaging

Shows a tree structure where several conventional packaging methods, such as creating a tree structure, traversing judgment.

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

public class ThreeUtil {
    /**
     * 递归创建树形结构
     */
    private static List<ThreeNode> getTree(List<ThreeNode> nodeList, Integer parentId) {
        List<ThreeNode> threeNodeList = new ArrayList<>() ;
        for (ThreeNode entity : nodeList) {
            Integer nodeId = entity.getId() ;
            Integer nodeParentId = entity.getParentId() ;
            if (parentId.intValue() == nodeParentId.intValue()) {
                List<ThreeNode> childList = getTree(nodeList,nodeId) ;
                if (childList != null && childList.size()>0){
                    entity.setChildNode(childList);
                    entity.setChildNodeSize(childList.size());
                }
                threeNodeList.add(entity) ;
            }
        }
        return threeNodeList ;
    }

    /**
     * 获取指定子节点
     */
    private static List<ThreeNode> getChildTree (Integer id,List<ThreeNode> nodeList){
        List<ThreeNode> resultList = new ArrayList<>();
        for (ThreeNode entity : nodeList) {
            if (entity.getParentId().intValue() == id) {
                List<ThreeNode> childList = getChildTree(entity.getId(),nodeList) ;
                entity.setChildNode(childList);
                entity.setChildNodeSize(childList.size());
                resultList.add(entity) ;
            }
        }
        return resultList ;
    }

    /**
     * 遍历树形结构
     */
    private static transient List<Integer> treeIdList = new ArrayList<>() ;
    private static List<Integer> getTreeInfo (List<ThreeNode> treeList){
        for (ThreeNode entity : treeList) {
            if (entity.getChildNodeSize()!=null && entity.getChildNodeSize()>0){
                getTreeInfo(entity.getChildNode());
            }
            treeIdList.add(entity.getId());
        }
        return treeIdList ;
    }

    /**
     * 判断节是否是叶子节点
     */
    private static boolean hasChildNode (Integer id,List<ThreeNode> nodeList){
        for (ThreeNode entity:nodeList){
            if (entity.getParentId().intValue() == id){
                return true ;
            }
        }
        return false ;
    }

    public static void main(String[] args) {
        List<ThreeNode> threeNodeList = new ArrayList<>() ;
        threeNodeList.add(new ThreeNode(1,"节点A",0)) ;
        threeNodeList.add(new ThreeNode(2,"节点B",1)) ;
        threeNodeList.add(new ThreeNode(3,"节点C",1)) ;
        threeNodeList.add(new ThreeNode(4,"节点D",1)) ;
        threeNodeList.add(new ThreeNode(5,"节点E",2)) ;
        threeNodeList.add(new ThreeNode(6,"节点F",2)) ;
        // 测试1
        List<ThreeNode> getTree = getTree(threeNodeList,0) ;
        System.out.println(getTree);
        // 测试2
        // List<ThreeNode> getChildTree = getChildTree(2,threeNodeList) ;
        // System.out.println(getChildTree);
        // 测试3
        List<Integer> treeIdList = getTreeInfo(getTree) ;
        System.out.println(treeIdList);
        // 测试4
        System.out.println(hasChildNode(2,threeNodeList)) ;
    }
}

Fourth, the source address

GitHub·地址
https://github.com/cicadasmile
GitEE·地址
https://gitee.com/cicadasmile

Recursive algorithm based on the traffic scenario, the tree structure data, encapsulating the solution

Guess you like

Origin blog.51cto.com/14439672/2464221
Recommended