What are inorder, preorder, and postorder traversals of the tree
F / \ D R \ E

3 4 + 5 * 3 4 5 * +
Reverse Polish notation of expression


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.inorder(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();
visitclass 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;
}
}
