So, I have written a method of printing a Binary Search Tree, however I want to save it in a variable of type String, and not print it anymore, so I tried to save the result in a local variable, however each time I call the function it does not append result correctly, because each time I call it, it is set to null. Here is my code:
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);
}
}}
The output should looks like this with printing it:
However, after the execution the outPut string is always empty.
So, how can I save the result in a String to a local variable?
You should not collect the string in a field. Instead, you should make the method return the string.
Like so:
public String toString() {
return toString("", "", "", "");
}
public String toString(String prefix, String left, String mid, String right) {
String indent = " ".repeat(String.valueOf(data).length());
String treeRepr = prefix + mid + data
+ " ┐┘┤".charAt((leftChild != null ? 2 : 0)
+ (rightChild != null ? 1 : 0));
if (leftChild != null) {
treeRepr = leftChild.toString(prefix + left + indent, " ", "┌", "│")
+ "\n"
+ treeRepr;
}
if (rightChild != null) {
treeRepr = treeRepr
+ "\n"
+ rightChild.toString(prefix + right + indent, "│", "└", " ");
}
return treeRepr;
}
If you then want to print the tree, instead of doing root.print()
, you call the toString
method:
System.out.println(root.toString());