Hi coders,
I create a BSTree but i don't know if it is right.
I only want to create a bstree with Strings, nothing else.
my code:
import java.util.Scanner;
class Node {
private Node left;
private String number;
private Node right;
public Node() {
left = null;
number = "0";
right = null;
}
public Node(String x) {
left = null;
number = x;
right = null;
}
public String getNumber() {
return number;
}
public Node getLeft() {
return left;
}
public Node getRight() {
return right;
}
public void setNum(String x){
number = x;
}
public void setLeft(Node leftNode) {
left = leftNode;
}
public void setRight(Node rightNode) {
right = rightNode;
}
}
class BST{
private Node root;
public BST(){
root = null;
}
public boolean isEmpty(){
return root == null;
}
public void insert(String x){
insertData(x, root);
}
private void insertData(String n, Node p){
if(p == null){
p = new Node(n);
root = p;
} else if(n.compareTo(p.getNumber()) < 0){
if(p.getLeft() == null){
p.setLeft(new Node(n));
} else {
p = p.getLeft();
insertData(n,p);
}
} else {
if(p.getRight() == null){
p.setRight(new Node(n));
} else {
p = p.getRight();
insertData(n, p);
}
}
}
}
public class BinarySearchTree{
public static void main(String[] args){
BST tree = new BST();
Scanner in = new Scanner(System.in);
for (int y=0; y<5;y++){
String x = in.nextLine();
tree.insert(x);
}
}
}