There is basically the same question on this site except it says dont post questions to questions here is a link. Binary Tree Recursive Function
I need to print out a binary tree that looks like this but for an arbitrary size:
--------x-------
----x-------x---
--x---x---x---x-
-x-x-x-x-x-x-x-x
xxxxxxxxxxxxxxxx
however when i execute the code outputs errors along with an endless print
:::X:::::X::X:XXXXX
and there is a blue line under this which i can click on and it brings up a window saying "source not found for" with endless X's
at sun.nio.cs.SingleByte.withResult(Unknown Source)
at sun.nio.cs.SingleByte.access$000(Unknown Source)
at sun.nio.cs.SingleByte$Encoder.encodeArrayLoop(Unknown Source)
at sun.nio.cs.SingleByte$Encoder.encodeLoop(Unknown Source)
at java.nio.charset.CharsetEncoder.encode(Unknown Source)
at sun.nio.cs.StreamEncoder.implWrite(Unknown Source)
at sun.nio.cs.StreamEncoder.write(Unknown Source)
at java.io.OutputStreamWriter.write(Unknown Source)
at java.io.BufferedWriter.flushBuffer(Unknown Source)
at java.io.PrintStream.write(Unknown Source)
at java.io.PrintStream.print(Unknown Source)
at BinaryBuilder.display(BinaryBuilder.java:25)
at BinaryBuilder.display(BinaryBuilder.java:31)
at BinaryBuilder.display(BinaryBuilder.java:31)
the code i have so far is just not working properly and i have had problems with recursion and understanding the order of the stack frames executing. Please help i thought i was on the right track using the row to return from the recursion. I need some guidance and a push in the right direction :)
import java.util.Scanner;
public class BinaryBuilder {
int levels = 0;
int width = 0;
int leaves = 0;
Scanner sn = new Scanner(System.in);
public BinaryBuilder() {
//prt("how many leaves?");
//leaves = sn.nextInt();
//levels = (int)Math.sqrt((double)leaves);
}
public void setLevelLeaves(int l,int le){
levels = l;
leaves = le;
}
public void display(int left, int right, int row){
int i =left;
int mid = (left+right)/2; //maybe a +1
if(row>levels){
return;
}
while(i <= right){
if(i==mid){
System.out.print("X");
}else{
System.out.print(":");
}
i++;
}
display(left, mid, row++);
display(mid, right, row++);
}
public void prt(String n){
System.out.println(n);
}
}
Main
public class PartBTest {
public PartBTest() {
}
public static void main(String[] args) {
BinaryBuilder bb = new BinaryBuilder();
//bb.prt("width will be reduced to a factor of 2");
bb.setLevelLeaves(3, 8);
bb.display( 0, bb.leaves-1, 0);
}
}
Happy coding :}