package brs.visitor; import brs.*; import rac.*; import fp.*; /** * Processed the tree nodes via depth-first traversal. * Uses a LIFO stack. * @author DXN */ public class DepthFirst implements IVisitor { private IRAContainer _stack= new LRSStackFactory().makeRAC(); private ILambda _f; private Object _acc; // accumulated result. // IRAContainer visitor to go through the stack and process each tree // in the queus with a given BiTree visitor. private IRACVisitor _processS = new IRACVisitor() { public Object emptyCase(IRAContainer s, Object treeVis) { return _acc; } public Object nonEmptyCase(IRAContainer s, Object treeVis) { ((BiTree)s.get()).execute((IVisitor)treeVis, null); return s.execute(this, treeVis); } }; public DepthFirst(ILambda f) { _f = f; } /** */ public Object emptyCase(BiTree host, Object b) { return b; } /** * Prints the root data, saves the left and right subtrees in _stack * and "process" _stack. */ public Object nonEmptyCase(BiTree host, final Object b) { _stack.put(host.getLeftSubTree()); _stack.put(host.getRightSubTree()); _acc = _f.apply(host, b); return _stack.execute(_processS, new IVisitor() { public Object emptyCase(BiTree h, Object nu) { return b; } public Object nonEmptyCase(final BiTree h, Object nu) { _stack.put(h.getLeftSubTree()); _stack.put(h.getRightSubTree()); _acc = _f.apply(h, _acc); return _acc; } }); } /** * Simple test code. */ public static void main(String[] args) { BiTree t0 = new BiTree(); t0.insertRoot(new Integer(1)); BiTree t1 = new BiTree(); t1.insertRoot(new Integer(2)); BiTree t2 = new BiTree(); t2.insertRoot(new Integer(3)); t0.setLeftSubTree(t1); t0.setRightSubTree(t2); t1.getLeftSubTree().insertRoot(new Integer(4)); t1.getLeftSubTree().getRightSubTree().insertRoot(new Integer(6)); t2.getRightSubTree().insertRoot(new Integer(5)); t2.getRightSubTree().getLeftSubTree().insertRoot(new Integer(7)); System.out.println("t0 is: \n" + t0 + "\n"); System.out.println("Depth first printing:"); ILambda f = new ILambda() { public Object apply(Object... args) { System.out.print("" + args[1] + ((BiTree)args[0]).getRootDat()); return " "; } }; t0.execute(new DepthFirst(f), ""); System.out.println("\nDepth first adding:"); ILambda add= new ILambda() { public Object apply(Object... args) { return (Integer)args[1] + (Integer)((BiTree)args[0]).getRootDat(); } }; System.out.println(t0.execute(new DepthFirst(add), 0)); System.out.println("\nDone!"); } }