/* * * Very basic program has methods for creating * trees and inserting nodes. The methods that * do the work of printing the tree are listed * below: * * treePrintMaster() * getLevels() * treePrint() * * * */ class PrintBinTree { char value; PrintBinTree left; PrintBinTree right; PrintBinTree(char c) { value = c; left = null; right = null; } PrintBinTree() { left = null; right = null; } public void insert(char c) { if(c < value) { if(left == null) { left = new PrintBinTree(c); } else { left.insert(c); } } else if(c > value) { if(right == null) { right = new PrintBinTree(c); } else { right.insert(c); } } } /* treePrintMaster() accepts the tree and controls the access to the other two methods. A for loop passes tree to getLevels() to obtain the number of levels in the tree and uses it as the condition. Then the tree is passed to treePrint() which prints the nodes at the current level. */ public static void treePrintMaster(PrintBinTree tree){ for(int i=0; i < tree.getLevels(0,0)+1; i++){ tree.treePrint(0, i); System.out.println(); } } /* getLevels() traverses the tree and counts the number of levels tree and returns it to treePrintMaster() */ int getLevels(int level, int temp) { if(level > temp){ temp = level; } if (right != null){ temp = right.getLevels(level + 1, temp); } if (left != null){ temp = left.getLevels(level + 1, temp); } return temp; } /* treePrint() traverses the tree and prints nodes if the node's level matches the current level */ void treePrint(int level, int levels) { if (left != null){ left.treePrint(level + 1, levels); }else{ System.out.print(" "); } if(level == levels){ System.out.print(value); } if (right != null){ right.treePrint(level + 1, levels); }else{ System.out.print(" "); } } public static void main(String args[]){ PrintBinTree tree = new PrintBinTree(); tree.insert('c'); tree.insert('a'); tree.insert('e'); tree.insert('d'); tree.insert('b'); treePrintMaster(tree); }//end main }//end class