这个网站上基本上有同样的问题,除了它说不要在问题中发布问题这里是一个链接。 二叉树递归函数
我需要打印出一个看起来像这样但任意大小的二叉树:
--------x-------
----x-------x---
--x---x---x---x-
-x-x-x-x-x-x-x-x
xxxxxxxxxxxxxxxx
但是,当我执行代码时会输出错误以及无休止的打印
:::X:::::X::X:XXXXX
在它下面有一条蓝线,我可以点击它,它会弹出一个窗口,上面写着“找不到源”,上面有无尽的 X
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)
到目前为止,我的代码无法正常工作,并且我在递归和理解堆栈帧执行顺序方面遇到了问题。请帮助我认为我在正确的轨道上使用该行从递归中返回。我需要一些指导并朝着正确的方向前进:)
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);
}
}
主要的
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);
}
}
快乐编码:}