public class Demo2 { public static void main(String[] args){ Tree sampleTree = new Tree("dog", new Tree("bat", null, new Tree("camel", null, null)), new Tree("mouse", null, null)); // The outermost procedure has a static link pointing at a frame // containing any global variables. GlobalFrame globals = new GlobalFrame(); String result = prettyprint(new PrettyprintFrame(globals), sampleTree); System.out.println(result); } static String prettyprint(PrettyprintFrame fp, Tree tree){ fp.output = ""; show(new ShowFrame(fp), 0, tree); return fp.output; } static void write(WriteFrame fp, String s){ fp.staticLink.output = fp.staticLink.output + s; } static void show(ShowFrame fp, int nArg, Tree t){ fp.n = nArg; // store in frame since it escapes if(t == null){ indent(new IndentFrame(fp), "."); } else { indent(new IndentFrame(fp), t.key); show(new ShowFrame(fp.staticLink), fp.n + 1, t.left); show(new ShowFrame(fp.staticLink), fp.n + 1, t.right); } } static void indent(IndentFrame fp, String s){ for(int i = 1; i <= fp.staticLink.n; i++){ write(new WriteFrame(fp.staticLink.staticLink), " "); } fp.staticLink.staticLink.output = fp.staticLink.staticLink.output + s; write(new WriteFrame(fp.staticLink.staticLink), "\n"); } } class Tree { String key; Tree left, right; Tree(String key, Tree left, Tree right){ this.key = key; this.left = left; this.right = right; } } class GlobalFrame { // any globals would go in here; Program 6.3 has none } class PrettyprintFrame { GlobalFrame staticLink; String output; // this is the one escaping variable PrettyprintFrame(GlobalFrame staticLink){ this.staticLink = staticLink; } } class WriteFrame { PrettyprintFrame staticLink; // no escaping variables WriteFrame(PrettyprintFrame staticLink){ this.staticLink = staticLink; } } class ShowFrame { PrettyprintFrame staticLink; int n; // escaping variable ShowFrame(PrettyprintFrame staticLink){ this.staticLink = staticLink; } } class IndentFrame { ShowFrame staticLink; // no escaping variables IndentFrame(ShowFrame staticLink){ this.staticLink = staticLink; } }