So, I have create Binary Search Tree and added the only method "add", which adds inputs to the tree. Here is my code for TreeNode:
static class TreeNode{
private int data;
private TreeNode leftChild;
private TreeNode rightChild;
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 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;
}}
Here is my Code for BinaryTree:
static class BinaryTree{
private TreeNode root;
public void insert(int data){
if(root == null){
this.root = new TreeNode(data);
}else{
root.add(data);
}
}}
I want to make a method, which outputs the hole binary tree with lines for example: If the inputs are {102, 10, 180, 2, 100, 140, 1000}, I want to output the binary tree as a String with lines like this:
Any suggestions, how to implement a method which prints the binary Tree?