CSC301: Iterative DFS contrasted with BFS [9/9] Previous pageContents

// DFS -- mark when pushing
public void printPre () {
    Stack<Node> stack = new Stack<> ();
    HashSet<Node> marked = new HashSet<> ();
    if (root != null) { stack.push (root); marked.add (root); }
    while (!stack.isEmpty()) {
        Node n = stack.pop ();
        StdOut.print (n.val + " ");
        for (Node child : n.children) {
            if (!marked.contains (child))
                { stack.push (child); marked.add (n); }
        }
    }
    StdOut.println ();
}
  // BFS -- mark when enqueuing
  public void printLevel () {
      Queue<Node> queue = new Queue<> ();
      HashSet<Node> marked = new HashSet<> ();
      if (root != null) { queue.enqueue (root); marked.add (root); }
      while (!queue.isEmpty()) {
          Node n = queue.dequeue();
          StdOut.print (n.val + " ");
          for (Node child : n.children) {
              if (!marked.contains (child))
                  { queue.enqueue (child); marked.add (n); }
          }
      }
      StdOut.println ();
  }

Previous pageContents