I've been looking for a way to complete this non-recursive method for hours. Our programming teacher has asked us to complete both a recursive and a non-recursive implementation of the same method, used to display the BinaryHeap in the console (I use Eclipse).
Here's my code for my methods:
public String nonRecursivePrintFancyTree()
{
String outputString = "";
/**********I DON'T KNOW WHAT TO DO HERE**********/
return outputString;
}
public String printFancyTree()
{
return printFancyTree( 1, "");
}
private String printFancyTree(int index, String prefix)
{
String outputString = "";
outputString = prefix + "|__";
if( index <= currentSize )
{
boolean isLeaf = index > currentSize / 2;
outputString += array[ index ] + "\n";
String _prefix = prefix;
if( index%2 == 0 )
_prefix += "| "; // one | and two spaces
else
_prefix += " " ; // three spaces
if( !isLeaf )
{
outputString += printFancyTree( 2*index, _prefix);
outputString += printFancyTree( 2*index + 1, _prefix);
}
}
else
outputString += "null\n";
return outputString;
}
}
Completing the recursive method took me some time, but I can't figure out an easy way to complete the non-recursive method.
This is my main class, used to check if the methods work as they should:
public class Main
{
/**
* Main function of the class
*/
public static void main(String[] args)
{
// create a Heap with 22 elements and an equivalent array
int numItems = 22;
BinaryHeap<Integer> heap = new BinaryHeap<Integer>();
Integer [] items = new Integer[numItems];
int i;
int j;
// elements are inserted one by one
for (i = 11, j = 0; j != numItems; i = (i + 37), j++)
{
heap.insert(i);
items[j] = i;
i %= numItems;
}
heap.buildMaxHeap();
System.out.println("Recursive display:");
System.out.println(heap.printFancyTree());
System.out.println("Non recursive display:");
System.out.println(heap.nonRecursivePrintFancyTree()); //<------this method
}
Here's what the display should look like:
|__58
|__56
| |__53
| | |__50
| | | |__11
| | | |__39
| | |__48
| | |__46
| | |__43
| |__54
| |__47
| | |__40
| | |__38
| |__51
| |__49
| |__null
|__57
|__44
| |__41
| |__42
|__52
|__37
|__45
Basically, it should give me the same display for both the recursive and non-recursive methods. I've looked everywhere: on Google, this very website, on Oracle documentation, even my course's Manual (Data structures and Algorithm Analysis in JAVA, 3rd ed., Mark Allen Weiss) and i can't even find a single possible way to do this. My question is, what is a possible implementation of "nonRecursivePrintFancyTree" ? Thanks in advance.