// level order traversal of a tree
public void printLevel () {
Queue<Node> q = new Queue<> ();
q.enqueue (root);
while (!q.isEmpty ()) {
Node x = q.dequeue ();
if (x == null) continue;
StdOut.print (x.key + " ");
q.enqueue (x.left);
q.enqueue (x.right);
}
StdOut.println ();
}
|
// breadth first traversal of a graph
// mark when enqueuing
public void printLevel () {
Queue<Node> q = new Queue<> ();
HashSet<Node> marked = new HashSet<> ();
q.enqueue (root); marked.add (root);
while (!q.isEmpty ()) {
Node x = q.dequeue ();
if (x == null || marked.contains (x)) continue;
StdOut.print (x.key + " ");
q.enqueue (x.left); marked.add (x.left)
q.enqueue (x.right); marked.add (x.right)
}
StdOut.println ();
}
|