Depth-first traversal and breadth-first traversal of the hierarchical trees (Java implementation)

Depth-first traversal and breadth-first traversal of the hierarchical trees (Java implementation)

Depth-first traversal and breadth-first traversal actually is a kind of graph algorithms, multi-level tree can be seen as a special map, so many series of deep / wide traverse directly apply traversal methods to map the structure.

Engineering backend to store pages are usually multi-stage tree form of linkage category levels, this article provides an example of the depth and breadth traversal of traversal, when used as long as according to your business needs a little change can.

We know that traverse the recursive, non-recursive two ways. In the project, the general approach is to disable recursion, because it is very easy to stack recursion makes the system burst. At the same time, JVM also limits the maximum number of recursion, it is prone to abnormal StackOverflowError in your tree structure is very deep when it is best to adopt a non-recursive manner.

Node model

public class Node {
    //值
    public int value;
    //所有的子节点
    public ArrayList<Node> nexts;

    public Node(int value) {
        this.value = value;
    }
}

Depth-first traversal

English abbreviation for the depth-first search DFS namely Depth First Search. The procedure is brief for each possible path deep into the branch can not go any further so far, and each node can only be accessed once. Can be seen as a multilevel tree structure of FIG particular, the method is generally the same traversal, are to operate with the stack and Set.

The main steps:

  1. Prepare a set of stack structure and the structure of a Set, the stack for recording and children have not been traversed to the node, Set to record the history of traversal
  2. The first node is added to the stack and set in
  3. Get popped first node
  4. Began traversing the depth from the first node, the following sample code with annotations nearly be understood.
public static void dfs(Node node) {
    if (node == null) {
        return;
    }
    Stack<Node> stack = new Stack<>();
    HashSet<Node> set = new HashSet<>();
    stack.add(node);
    set.add(node);
    System.out.println(node.value);
    
    while (!stack.isEmpty()) {
        //弹栈获得一个节点
        Node cur = stack.pop();
        //查看这个节点的所有孩子
        for (Node next : cur.nexts) {
            //如果有孩子是之前没有遍历到的,说明这个节点没有深度遍历完
            if (!set.contains(next)) {
                //此节点与其孩子加入栈与Set中
                stack.push(cur);
                stack.push(next);
                set.add(next);
                System.out.println(next.value);
                break;
            }
        }
    }
}

Breadth-first traversal

Breadth-first search algorithm (also known as the breadth-first search) is one of the easiest search algorithm graph, this algorithm prototype algorithm also many important figure. For multi-series, it is the first to traverse all the children of the node, then traverse all children in child nodes, and then traverse to traverse a layer of a lower layer.

The main idea is to use a queue to all nodes in the next layer of the record, then sequentially traversing it.

public static void bfs(Node node) {
    if (node == null) {
        return;
    }
    Queue<Node> queue = new LinkedList<>();
    //用来注册已加入队列的节点——>防止重复添加节点
    HashSet<Node> set = new HashSet<>();
    queue.add(node);
    set.add(node);
    while (!queue.isEmpty()) {
        Node cur = queue.poll();
        System.out.println(cur.value);
        //将节点的所有下游节点加入到队列
        for (Node next : cur.nexts) {
            if (!set.contains(next)) {
                set.add(next);
                queue.add(next);
            }
        }
    }
}

Guess you like

Origin www.cnblogs.com/keeya/p/11487465.html