I'm trying to sort a BST alphabetically and I wrote an insert method if compareTo==-1
it goes to root.setLeft()
if compareTo==1
goes to root.setRigth()
but obviously when I run the program it doesn't start with any value so it's null and I'm getting NullPointerException, I know I have to start the comparison after I values but I can't figure out how to do that, also if I put a valid value in the constructor it doesn't insert values after that.
class BST{
Node insertNames(Node root, int data, String name, double salary){
if(root==null){
root=new Node();
root.setData(data);
root.setName(name);
root.setLeft(null); root.setRight(null);
}else{
if(name.compareTo(root.getName())==-1) root.setLeft(insertNames(root.getLeft(),data, name, salary));
else if(name.compareTo(root.getName())==1) root.setRight(insertNames(root.getRight(),data, name, salary));
}
return root;
}
void printInorder(Node node)
{
if (node == null)
return;
/* first recur on left child */
printInorder(node.left);
/* then print the data of node */
System.out.print(node.getName() + " ");
/* now recur on right child */
printInorder(node.right);
}
}
class Node{
int data;
Node left;
Node right;
String name;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public Node(){
}
public int getData(){
return data;
}
public void setData(int data){
this.data=data;
}
public Node getLeft(){
return left;
}
public void setLeft(Node left){
this.left=left;
}
public Node getRight(){
return der;
}
public void setRight(Node Right){
this.right=right;
}
class main{
public static void main(String[] args){
BST b1=new BST();
Node root=new Node();
/*Here the root is null, I think this causing the NullPointerException, but if a have a constructor with parameters it doesn't insert any name instead the one that I put in the parameter*/
b1.insertNames(root, 0, "Roy", 0);
b1.insertNames(root, 0, "Joseph", 0);
b1.printInorder(root);
}
}