/** * A simple mechanism for printing binary trees in "outline form". In * this form, the tree *
 *     A
 *   /   \
 *  B     E
 *   \   / \
 *    Q  T  S
 * 
 * would be printed as
 * 
 *    A
 *      B
 *        -
 *        Q
 *      E
 *        T
 *        S
 * 
*/ public class BinaryTreePrinter { // +---------+------------------------------------------------- // | Methods | // +---------+ /** * Print a tree to a particular output object. */ public void printTree(SimpleOutput out, BinaryTree tree) { printTree(out, tree.rootCursor()); } // printTree(SimpleOutput, BinaryTree) /** * Print the portion of a tree given by a cursor to a particular * output object. */ public void printTree(SimpleOutput out, BinaryTreeCursor subRoot) { printTree(out, subRoot, ""); } // printTree(SimpleOutput, BinaryTreeCursor) // +---------+------------------------------------------------- // | Helpers | // +---------+ /** * Print the portion of a tree given by a cusror to a particular * output object, indended a specified amount. */ protected void printTree( SimpleOutput out, BinaryTreeCursor subRoot, String indent) { // Sanity check. Make sure the cursor is on the tree. if (!subRoot.onTree()) { out.println(indent + "?"); return; } // Print the value in the current node. out.println(indent + subRoot.getValue().toString()); // If we're not at a leaf, print the left and right subtrees, // indented slightly more. if (!subRoot.onLeaf()) { // If it has a left subtree, print it. if (subRoot.hasLeftChild()) printTree(out, subRoot.getLeftChild(), indent + " "); // If it doens't have a left subtree, print a dash. else out.println(indent + " -"); // If it has a right subtree, print it. if (subRoot.hasRightChild()) printTree(out, subRoot.getRightChild(), indent + " "); // If it doens't have a right subtree, print a dash. else out.println(indent + " -"); } // If we're not at a leaf. } // printTree(SimpleOutput, BinaryTreeCursor, String) } // class BinaryTreePrinter