java - 如何在 Java 中打印二叉树?
问题描述
public class BinaryNode<T> {
protected T data;
protected BinaryNode<T> left;
protected BinaryNode<T> right;
public BinaryNode(T element) {
if (element == null)
throw new IllegalArgumentException();
this.data = element;
left = null;
right = null;
}
public int height() {
int leftH = -1, rightH = -1;
if (left != null)
leftH = left.height();
if (right != null)
rightH = right.height();
return Math.max(leftH, rightH) + 1;
}
public int size() {
int leftS = 0, rightS = 0;
if (left != null)
leftS = left.size();
if (right != null)
rightS = right.size();
return leftS + rightS + 1;
}
private String spaces(int count){
String spaces="";
while(count>0){
spaces=spaces+" ";
count=count-1;
}
return spaces;
}
public String toString(){
String str="";
if(left!=null)
str=str+spaces(left.height())+left.toString(); //left
str=str+spaces(left.height()-1)+data.toString()+"\n";//root
if(right!=null)
str=str+spaces(right.height())+right.toString();//right
return str;
}
}
我需要在 BinaryNode 类中构建 toString 函数。该方法有效,因此如果我们打印它返回的字符串,我们将在树中的每个顶点得到一个打印行。在这一行中,将出现 2*d 个空格,其中 d 是树中顶点的深度,然后将打印有关顶点的信息(在同一行中)。例如对于以下 BinarySearchTree(BinarySearchTree 中的示例,因此更容易理解它需要如何打印):
BinarySearchTree t4 = new BinarySearchTree(c);
t4.insert(8);
t4.insert(7);
t4.insert(6);
t4.insert(5);
t4.insert(4);
t4.insert(3);
t4.insert(2);
t4.insert(1);
System.out.println("----------t4:----------\n" + t4);
toString 需要打印:
----------t4:----------
1
2
3
4
5
6
7
8
我在上面写了我创建的代码但它不起作用,问题是我知道它为什么不起作用但我不知道如何修复它。基本上,我不知道该怎么做。
感谢任何帮助。
解决方案
为有需要的人提供解决方案:
private String spaces(int count){
String spaces="";
while(count>0){
spaces=spaces+" ";
count=count-1;
}
return spaces;
}
private String toString(int depth){
String str="";
if(left!=null)
{
str=str+left.toString(depth+1);
}
str=str+spaces(depth)+data.toString()+"\n";
if(right!=null)
{
str=str+right.toString(depth+1);
}
return str;
}
private String toString(String str){
if(left!=null)
str=str+left.toString(" ");
str=str+data.toString()+"\n";
if(right!=null)
str=str+right.toString(" ");
return str;
}
推荐阅读
- python - Python函数读取视频并转换为帧
- pandas - 如何在熊猫中执行反连接或左外连接(基于多个键获取数据集中不在另一个数据集中的所有行)
- ruby - 如何将日期转换为字符串单词,例如输入 11-12-2001 输出应该是 11 月 11 日 2001 年,用红宝石表示
- xml - 从 XML 查询返回的空列表
- angular - 为 PathLocationStrategy 的 Angular CLI 开发服务器配置代理设置的正确方法是什么
- python - 单击 QDockWidget 的选项卡时的通知?
- ios - 将纬度和经度放在 mapView 上
- ios - Apple 拒绝应用程序:5.2.2 法律、知识产权 - 第三方网站/服务
- javascript - 在 React 中将 Object 转换为 JSON 并下载为 .json 文件
- python - Python意外行为..同时附加到列表类属性