To finish off my Java Algorithm tutorial, I thought it would be interesting to cover solving programming problems in general. So, in this tutorial I’ll answer the question I’ve been getting, which is how to print a tree data structure.
On our journey to better understand how to solve problems I will first solve the basic problem. Then in the next part of the tutorial I will perfect printing any type of tree. The code below will better explain the process of solving this problem.
If you like videos like this, it helps to tell Google+ with a click here [googleplusone]
Code From the Video
4 ROW TREE _______1 ___1_______1 _1___1___1___1 1_1_1_1_1_1_1_1 1st Row Indent 7 Spaces 0 2nd Row Indent 3 Spaces 7 3rd Row Indent 1 Spaces 3 4th Row Indent 0 Spaces 1 Indent : -2^-n * (-16+2^n) start with 1 Spaces : 0 and then whatever Indent was First Index Per Row 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 .5 * (-2 + (Math.pow(2, iteration))) Items Per Row 1, 2, 4, 8 Math.pow(2, iteration - 1) Max Index Per Row indexToPrint + itemsPerRow Indent Number Indent Number Space Number Indent Number Space Number Space... I need 1 index followed by multiple numbers & spaces every time
public void printTree(int rows) { int spaces = 0; int iteration = 1; while (iteration <= rows) { int indent = (int) Math .abs(((Math.pow(-2, -iteration)) * (-16 + (Math.pow(2, iteration))))); int indexToPrint = (int) (.5 * (-2 + (Math.pow(2, iteration)))); int itemsPerRow = (int) (Math.pow(2, iteration - 1)); int maxIndexToPrint = indexToPrint + itemsPerRow; for (int j = 0; j < indent; j++) System.out.print(" "); for (int l = indexToPrint; l < maxIndexToPrint; l++) { System.out.print(theHeap[l].key); for (int k = 0; k < spaces; k++) System.out.print(" "); } spaces = indent; iteration++; System.out.println(); } }
Leave a Reply