Commit f3ab1023 authored by Ari Trachtenberg's avatar Ari Trachtenberg
Browse files

Nicer pretty-printing of BST.

parent 6047caf8
Loading
Loading
Loading
Loading
+5 −20
Original line number Diff line number Diff line
@@ -89,46 +89,31 @@ public class BST<keyType extends Comparable<keyType> > {
     * Return the BST rooted at this node as a human-readable string
     */
    final public String toString() {
        return toString(0);
        return toString("|");
    }

    /**
     * Return the BST rooted at this node as a human-readable string,
     * indented by <code>depth</code> characters
     *
     * @param depth How many characters to indent.
     * @param prefix The current prefix for the subtree being printed
     */
    final String toString(int depth) {
    final String toString(String prefix) {
        String result = "";

        // output the key
        result += key + "\n";

        // recurse
        if (left != null)
            result += repeatDelim(depth) + "L" + left.toString(depth + 1);
        if (right != null)
            result += repeatDelim(depth) + "R" + right.toString(depth + 1);

        result += prefix + "->" + (left == null ? "\n" : left.toString(prefix.concat("  |")));
        result += prefix + "->" + (right == null ? "\n":right.toString(prefix.replace("  |","   ").concat("  |")));
        return result;
    }

    /**
     * @return a string containing the repetition of the {@link #DELIM} character <code>depth</code> times.
     */
    private String repeatDelim(int depth) {
        StringBuilder result = new StringBuilder(depth);
        for (int ii = 0; ii < depth; ii++)
            result.append(DELIM);
        return result.toString();
    }


    // FIELDS
    protected keyType key; // the key stored by this node
    protected BST<keyType> left;    // the left child of this node
    protected BST<keyType> right;   // the right child of this node

    // CONSTANTS
    final char DELIM = '-'; // a delimiter for printing
}
+7 −3
Original line number Diff line number Diff line
@@ -6,8 +6,12 @@ import java.util.Arrays;
class Main {

    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1, 3, 2, 5, 4));
        BST<Integer> test = new BST<>(numbers);
        System.out.println("Your BST is:\n"+test);
        ArrayList<Integer> intElements = new ArrayList<>(Arrays.asList(3,1,4,1,5,9,2,6));
        ArrayList<String> strElements = new ArrayList<>(Arrays.asList("Hi","Aardvark","Buy","me"));
        BST<Integer> intTest = new BST<>(intElements);
        BST<String> strTest = new BST<>(strElements);

        System.out.println("Your int BST is:\n"+intTest);
        System.out.println("Your string BST is:\n"+strTest);
    }
}