
What is the inorder traversal of the tree
F / \ D R \ E
public void print()
{
print(root);
}
private static void print(Node parent)
{
if (parent == null) { return; }
print(parent.left);
System.out.print(parent.data + " ");
print(parent.right);
}
What are preorder and postorder traversals of the tree
F / \ D R \ E

3 4 + 5 * 3 4 5 * +


Suppose you have two directory trees and you want to find out whether they contain the same subdirectories, each of which contains the same files. Should you traverse using
public interface Visitor
{
void visit(Object data);
}
private static void preorder(Node n, Visitor v)
{
if (n == null) { return; }
v.visit(n.data);
for (Node c : n.children) { preorder(c, v); }
}
public void preorder(Visitor v) { preorder(root, v); }
public static void main(String[] args)
{
BinarySearchTree bst = . . .;
class ShortNameCounter implements Visitor
{
public int counter = 0;
public void visit(Object data)
{
if (data.toString().length() <= 5) { counter++; }
}
}
ShortNameCounter v = new ShortNameCounter();
bst.preorder(v);
System.out.println("Short names: " + v.counter);
}
Push the root node on a stack. While the stack is not empty Pop the stack; let n be the popped node. Process n. Push the children of n on the stack, starting with the last one.


Suppose you have a binary tree of height n > 1. Can its depth-first traversal ever be the same as its breadth-first traversal?
TreeSet<String> t = . . . Iterator<String> iter = t.iterator(); String first = iter.next(); String second = iter.next();
class BreadthFirstIterator
{
private Queue<Node> q;
public BreadthFirstIterator(Node root)
{
q = new LinkedList<Node>();
if (root != null) { q.add(root); }
}
public boolean hasNext() { return q.size() > 0; }
public Object next()
{
Node n = q.remove();
for (Node c : n.children) { q.add(c); }
return n.data;
}
}