DFS深度优先遍历代码模板

深度优先遍历DFS用栈

递归写法:

Set<Node> visited = new HashSet<>();

public void dfs(Node root, Set<Node> visited) {
    if (visited.contains(root)) {//terminator
        // already visited
        return;
    }
    visited.add(root);

    // process current node here.
    for (Node nextNode : node.children) {
        if (!visited.contains(nextNode)) {
            dfs(nextNode, visited);
        }
    }
}

 

非递归写法:

public int[] dfs(Node root){ 
    if (root == null) {
        return new int[0];
    }
    Set<Node> visited = new HashSet<>();
    Stack<Node> stack = new Stack<>();
    stack.push(root);

    while (!stack.isEmpty()) { 
        Node node = stack.pop();
        visited.add(node);

        process (node); 
        List<Node> nodes = generate_related_nodes(node);
        stack.addAll(nodes); 

        // other processing work 
        // ...
    }
}

 

posted @ 2020-07-17 16:48  gaopengpy  阅读(807)  评论(0编辑  收藏  举报