// TREE code
// prefix order traversal
public void printPre () {
if (root != null) printPre (root);
StdOut.println ();
}
private static void printPre (Node n) {
StdOut.print (n.val + " ");
for (Node child : n.children) {
printPre (child, marked);
}
}
// level order traversal
public void printLevel () {
Queue<Node> queue = new Queue<>();
if (root != null) queue.enqueue(root);
while (!queue.isEmpty()) {
Node n = queue.dequeue();
StdOut.print (n.val + " ");
for (Node child : n.children) {
queue.enqueue(child);
}
}
StdOut.println ();
}
}
|
// GRAPH code
// preorder traversal
public void printPre () {
if (root != null) printPre (root, new HashSet<Node> ());
StdOut.println ();
}
private static void printPre (Node n, HashSet<Node> marked) {
StdOut.print (n.val + " ");
marked.add (n);
for (Node child : n.children) {
if (!marked.contains (child))
printPre (child, marked);
}
}
// level order traversal
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 ();
}
|