I did a code that take as input integers, for example: 123 11 200 1 100 150 2000
and need to output a binary tree, in this form:
┌1
┌11┤
│ └100
123┤
│ ┌150
└200┤
└2000
but in my code output is:
0┐
│ ┌1
│ ┌11┤
│ │ └100
└123┤
│ ┌150
└200┤
└2000
At he root appear a zero and I do not know why.
This is my code. I consider that the problem is in the add()
method, but do not know how to solve it. I will be grateful for help.
public class TreeNode extends BinaryTree implements PrintableTree {
private int i;
private TreeNode leftChild;
private TreeNode rightChild;
public TreeNode(int i) {
this.i = i;
}
public TreeNode() {
}
@Override
public void add(int i) {
if (i > this.i) {
if (this.rightChild == null) {
this.rightChild = new TreeNode(i);
} else {
this.rightChild.add(i);
}
} else {
if (this.leftChild == null) {
this.leftChild = new TreeNode(i);
} else {
this.leftChild.add(i);
}
}
}
public int getI() {
return i;
}
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;
}
@Override
public String prettyPrint() {
StringBuilderPlus builder = new StringBuilderPlus();
prettyPrint(builder, "", "", "", "");
return builder.toString();
}
public void print() {
StringBuilderPlus res = new StringBuilderPlus();
prettyPrint(res, "", "", "", "");
}
public void prettyPrint(StringBuilderPlus result, String prefix, String left, String mid, String right) {
String indent = " ".repeat(String.valueOf(i).length());
if (leftChild != null) {
leftChild.prettyPrint(result, prefix + left + indent, " ", "┌", "│");
}
result.appendLine(prefix + mid + i
+ " ┐┘┤".charAt((leftChild != null ? 2 : 0)
+ (rightChild != null ? 1 : 0)));
if (rightChild != null) {
rightChild.prettyPrint(result, prefix + right + indent, "│", "└", " ");
}
}
}
public class StringBuilderPlus {
private StringBuilder sb;
public StringBuilderPlus(){
sb = new StringBuilder();
}
public void append(String str)
{
sb.append(str != null ? str : "");
}
public void appendLine(String str)
{
sb.append(str != null ? str : "").append(System.getProperty("line.separator"));
}
public String toString()
{
return sb.toString();
}
}
class BinaryTree {
private TreeNode root;
public void Print() {
if (root != null) {
root.print();
}
}
public void add(int i) {
if (root == null) {
root = new TreeNode(i);
} else {
root.add(i);
}
}
}
public interface PrintableTree {
void add(int i);
String prettyPrint();
static PrintableTree getInstance() {
return new TreeNode();
}
}