// BTPrintComplete - print a complete binary tree in "pretty print" form public class BTPrintComplete { public static void main(String[] args) { BTNode root; root = beginningTree(); /* * root.preorderPrint(); System.out.println(); root.inorderPrint(); * System.out.println(); root.postorderPrint(); root.print(0); */ prettyPrint(root, 50); } public static BTNode beginningTree() { BTNode root; BTNode child; root = new BTNode(1, null, null); child = new BTNode(2, null, null); root.setLeft(child); child = new BTNode(3, null, null); root.setRight(child); child = root.getLeft(); child.setLeft(new BTNode(4, null, null)); child.setRight(new BTNode(5, null, null)); child = child.getLeft(); child.setLeft(new BTNode(8, null, null)); child.setRight(new BTNode(9, null, null)); child = root.getRight(); child.setLeft(new BTNode(6, null, null)); child.setRight(new BTNode(7, null, null)); child = root.getLeft().getRight(); child.setLeft(new BTNode(0, null, null)); return root; } public static void prettyPrint(BTNode t, int n) { LinkedQueue> q = new LinkedQueue>(); BTNode node; int count = 1; q.add(t); while (!q.isEmpty()) { printChar(' ', n/2); // print one level for (int i = 0; !q.isEmpty() && i < count; i++) { node = q.remove(); if (node.getLeft() != null) q.add(node.getLeft()); if (node.getRight() != null) q.add(node.getRight()); System.out.print(node.getData()); printChar(' ', n); } // set up next level System.out.println(); count *= 2; n = n/2; } } public static void printChar(char c, int n) { for (int i = 0; i < n; i++) { System.out.print(c); } } }