// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.PrintStream;
import java.util.Arrays;

public class TreeNode<T extends Comparable<T>> {
    private T value;
    public TreeNode<T> left;
    public TreeNode<T> right;
    public TreeNode(T value) {
        this.value = value;
        this.left = null;
        this.right = null;
    }
    public T getValue() {
        return value;
    }
    public TreeNode<T> getLeft() {
        return left;
    }
    public TreeNode<T> getRight() {
        return right;
    }
    public void insert(T value) {
        int comp = value.compareTo(this.value);
        if(comp < 0) {
            if(left == null) {
                left = new TreeNode<T>(value);
            } else {
                left.insert(value);
            }
        } else if(comp > 0) {
            if(right == null) {
                right = new TreeNode<T>(value);
            } else {
                right.insert(value);
            }
        } else {
            throw new IllegalArgumentException("Value already in tree: " + value);
        }
    }
    public int count() {
        int res = 1;
        if(left != null) {
            res += left.count();
        }
        if(right != null) {
            res += right.count();
        }
        return res;
    }
    private void dump(String indent, PrintStream ps) {
        ps.println(indent + value + "(" + count() + ")");
        if(left != null) {
            left.dump(indent + "  ", ps);
        }
        if(right != null) {
            right.dump(indent + "  ", ps);
        }
    }
    public void dump(PrintStream ps) {
        dump("", ps);
    }
    private void fill(char[][] sq, int row, int offset, int width) {
        sq[row][offset+width/2] = value.toString().charAt(0);
        if(left != null) {
            left.fill(sq, row + 1, offset, width/2);
        }
        if(right != null) {
            right.fill(sq, row + 1, offset + width/2, width/2);
        }
    }
    public void print(PrintStream ps) {
        int h = (int)(2*Math.sqrt(count()));
        int w = (int)(16*Math.sqrt(count()));
        char[][] sq = new char[h][w];
        for(int i = 0; i < h; i++) {
            Arrays.fill(sq[i], ' ');
        }
        fill(sq, 0, 0, w);
        for(int i = 0; i < h; i++) {
            for(int j = 0; j < w; j++) {
                System.out.print(sq[i][j]);
            }
            System.out.println();
        }
    }
    public static void main(String[] args) {
        TreeNode<String> tree = new TreeNode<String>("F");
        tree.insert("B");
        tree.insert("A");
        tree.insert("C");
        tree.insert("H");
        tree.insert("J");
        tree.insert("G");
        tree.insert("D");
        tree.insert("E");
        tree.insert("I");
        tree.dump(System.out);
        tree.print(System.out);
    }
}
