package lab06_test; import java.util.*; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.text.*; public class DisplayTree { int data; // Node data stored as an int value. DisplayTree[] children = null; // Children stored in an array. void preorderDisplayText( int cur_offset, boolean same_line ) { /* Performs a preorder traversal to display the tree via text. * Inputs: cur_offset: gives the amount of space offset for the current node. same_line: if true, the current node is on the same line as previous node, print ' - ' and then display the node value. if false, the current node is on a separate line, print adequate space using print_space() then print ' \\ ' and the node value. Comments: Use System.out.printf("%2d", data); to allocate two characters for each node value. */ if( same_line ) { System.out.print(" - "); System.out.printf("%2d", data); } else { System.out.println(); printSpace(cur_offset); System.out.print(" \\ "); System.out.printf("%2d", data); } cur_offset = cur_offset + 5; if( children.length > 0 ) { children[0].preorderDisplayText( cur_offset, true ); for(int i = 1; i < children.length; i++ ) { children[i].preorderDisplayText( cur_offset, false ); } } } void printSpace(int length) { for( int i = 0; i < length; i++ ) System.out.print(" "); } int preorderDisplayGraphics(Graphics g, int x_offset, int y_offset ) { int dia = 40, x_jump = 70, y_jump = 50; drawNumberCircle( g, x_offset, y_offset, dia ); int new_x = x_offset + x_jump; int new_y = y_offset; if( children.length > 0 ) { for(int i = 0; i < children.length; i++ ) { drawLine(g, x_offset, y_offset, new_x, new_y, dia/2 ); new_y = y_jump + children[i].preorderDisplayGraphics(g, new_x, new_y); } new_y -= y_jump; } return new_y; } void drawNumberCircle(Graphics g, int x, int y, int dia) { g.setColor(Color.ORANGE); g.fillOval( x, y, dia, dia ); g.setColor(Color.RED); g.setFont(new Font("Verdana",Font.BOLD,15)); g.drawString( ""+data, x + dia/2 - 12, y + dia/2 +5 ); } void drawLine( Graphics g, int x1, int y1, int x2, int y2, int radius ) { x1 = x1 + radius; y1 = y1 + radius; x2 = x2 + radius; y2 = y2 + radius; double dist = Math.sqrt(Math.pow((x1 - x2), 2)+Math.pow((y1 - y2), 2)); double alpha1 = radius / dist; double alpha2 = (dist - radius) / dist; int xn1 = (int)(alpha1 * x1 + (1 - alpha1) * x2); int yn1 = (int)(alpha1 * y1 + (1 - alpha1) * y2); int xn2 = (int)(alpha2 * x1 + (1 - alpha2) * x2); int yn2 = (int)(alpha2 * y1 + (1 - alpha2) * y2); g.drawLine(xn1, yn1, xn2, yn2); } static Random rand = new Random(12345); DisplayTree( int height ) { data = rand.nextInt(99); int numChildren = rand.nextInt(4); if( height > 0 && numChildren > 0 ) { children = new DisplayTree[numChildren]; for(int i = 0; i < numChildren; i++ ) children[i] = new DisplayTree(height - 1); } else children = new DisplayTree[0]; } }