【发布时间】:2021-10-08 18:55:40
【问题描述】:
所以,我写了一个打印二叉搜索树的方法,但是我想把它保存在一个字符串类型的变量中,不再打印它,所以我尝试将结果保存在一个局部变量中,但是每个当我调用该函数时,它不会正确附加结果,因为每次调用它时,它都设置为 null。这是我的代码:
static class TreeNode {
private int data;
private TreeNode leftChild;
private TreeNode rightChild;
private String outPut;
public TreeNode(int data) {
this.data = data;
}
public void add(int data) {
if (data >= this.data) {
if (this.rightChild == null) {
this.rightChild = new TreeNode(data);
} else {
this.rightChild.add(data);
}
} else {
if (this.leftChild == null) {
this.leftChild = new TreeNode(data);
} else {
this.leftChild.add(data);
}
}
}
public void addOutput(String s){
this.outPut=this.outPut+s;
}
public void print() {
print("", "", "", "");
}
public void print(String prefix, String left, String mid, String right) {
String indent = " ".repeat(String.valueOf(data).length());
if (leftChild != null) {
leftChild.print(prefix + left + indent, " ", "┌", "│");
}
System.out.println(prefix + mid + data
+ " ┐┘┤".charAt((leftChild != null ? 2 : 0)
+ (rightChild != null ? 1 : 0)));
//Here i added method to append to a local string
addOutput(prefix + mid + data
+ " ┐┘┤".charAt((leftChild != null ? 2 : 0)
+ (rightChild != null ? 1 : 0)));
if (rightChild != null) {
rightChild.print(prefix + right + indent, "│", "└", " ");
}
}
public int getData() {
return data;
}
public void setLeftChild(TreeNode leftChild) {
this.leftChild = leftChild;
}
public void setRightChild(TreeNode rightChild) {
this.rightChild = rightChild;
}
public TreeNode getLeftChild() {
return leftChild;
}
public TreeNode getRightChild() {
return rightChild;
}
}
static class BinaryTree{
private TreeNode root;
public void pprint() {
if (root != null) {
root.print();
}
}
public void insert(int data){
if(root == null){
this.root = new TreeNode(data);
}else{
root.add(data);
}
}}
打印出来的输出应该是这样的:
但是,执行后输出字符串始终为空。
那么,如何将字符串中的结果保存到局部变量中呢?
【问题讨论】:
-
您不应该以
outPut开头的字段,这根本不是二叉树的一部分。您可以让print返回包含所有输出的String。 -
是的,但是如果该方法继续递归,我如何将其他字符串附加到该字符串?我的意思是,我在哪里可以存储该字符串变量?在 print 方法中是不可能的
-
在 实际 局部变量中,而不是字段中。你调用递归方法,获取它的返回值,将它与一些东西结合起来,然后返回那个串联。
标签: java string methods output local-variables