001 002 package brs; 003 004 /** 005 * Computes a String representation of the binary tree host so that it can be 006 * printed vertically. 007 * @author Dung X. Nguyen - Copyright 2000 - All rights reserved. 008 * @author Mathias Ricken - Copyright 2008 - All rights reserved. 009 */ 010 public class ToString<T> implements IVisitor<T,String,Void> { 011 private ToStringHelp<T> _toStringHelp = new ToStringHelp<T>(); 012 /** 013 * Returns "[]", a String representation of an empty binary tree. 014 * @param host an empty binary tree. 015 * @param nu not used. 016 * @return String 017 */ 018 public String emptyCase(BiTree<T> host, Void... nu) { 019 return "[]"; 020 } 021 022 /** 023 * Computes a String representation of the binary tree host so that it can 024 * be printed vertically. There is no '\n' at the end of the String. Passes 025 * appropriate leftmost leading String to a helper visitor to compute the 026 * String representations of the left and right subtrees. 027 * @param host a non-empty binary tree. 028 * @param nu not used. 029 * @return String 030 */ 031 public String nonEmptyCase(BiTree<T> host, Void... nu) { 032 String ls = host.getLeftSubTree().execute(_toStringHelp, "| "); 033 String rs = host.getRightSubTree().execute(_toStringHelp, " "); 034 return (host.getRootDat() + "\n" + ls + "\n" + rs); 035 // EXERCISE FOR STUDENTS: Rewrite using anonymous inner classes. 036 } 037 }