package binaryTree.visitor; import binaryTree.*; /** * Computes a String representation of the binary tree host so that it can be printed vertically. * @author Dung X. Nguyen - Copyright 2000 - All rights reserved. */ public class ToString implements IVisitor { public final static ToString Singleton = new ToString (); private ToString () { } /** * Returns "[]", a String representation of an empty binary tree. * @param host an empty binary tree. * @param input not used. * @return "[]". */ public Object emptyCase(BiTree host, Object input) { return "[]"; } /** * Computes a String representation of the binary tree host so that it can be printed vertically. * There is no '\n' at the end of the String. Passes appropriate leftmost leading String to * a helper visitor to compute the String representations of the left and right subtrees. * @param host a non-empty binary tree. * @param input not used. * @return (root + "\n" + * left subtree + "\n" + * right subtree) */ public Object nonEmptyCase(BiTree host, Object input) { String ls = (String) host.getLeftSubTree().execute(ToStringHelp.Singleton, "| "); String rs = (String)host.getRightSubTree().execute(ToStringHelp.Singleton, " "); return (host.getRootDat() + "\n" + ls + "\n" + rs); // EXERCISE FOR STUDENTS: Rewrite the above using anonymous inner classes. } }