Hey guys, trying to create a binary search tree (BST) and I dont know why but the program is not reading my insert method? When I am testing it, it shows that I did insert the number, yet when I do a check to see if the tree is empty the program says that it is empty.
Any ideas why?
//Node Class
import java.lang.*;
public class Node {
private Node left;
private int number;
private Node right;
public Node() {
left = null;
number = 0;
right = null;
}
public Node(int x) {
left = null;
number = x;
right = null;
}
public int getNumber() {
return number;
}
public Node getLeft() {
return left;
}
public Node getRight() {
return right;
}
public void setNum(int x){
number = x;
}
public void setLeft(Node leftNode) {
left = leftNode;
}
public void setRight(Node rightNode) {
right = rightNode;
}
}
//Binary Search Tree class
public class BST{
private Node root;
public BST(){
root = null;
}
/*
Checks to see if the tree is empty
@return - true for empty
*/
public boolean isEmpty(){
return root == null;
}
public void inOrder(){
inOrderHelper(root);
System.out.println("xx" + root.getNumber());
}
private void inOrderHelper(Node t){
if(t != null){
System.out.print("TESTING");
inOrderHelper(t.getLeft());
System.out.print(t.getNumber() + " ");
inOrderHelper(t.getRight());
} else
System.out.print("EMPTY");
}
public void insert(int x){
insertData(x, root);
}
private void insertData(int n, Node p){
if(p == null){
p = new Node(n);
System.out.print(p.getNumber() + " Inserted in Root ");
} else if(n < p.getNumber()){
if(p.getLeft() == null){
p.setLeft(new Node(n));
//System.out.print(p.getNumber() + " ");
} else {
p = p.getLeft();
insertData(n,p);
}
} else {
if(p.getRight() == null){
p.setRight(new Node(n));
//System.out.print(p.getNumber() + " ");
} else {
p = p.getRight();
insertData(n, p);
}
}
}
}
//Driver
import java.util.*;
public class BSTDrive{
public static void main(String[] args){
BST tree = new BST();
Scanner scan = new Scanner(System.in);
for(int i = 0; i <4; i++){
System.out.print("Enter Int: ");
int num;
num = scan.nextInt();
tree.insert(num);
tree.inOrder();
}
}
}
Here is a sample output that I get (along with the error). It's stating nullpointerexception but I clearly placed a value in the root node. :confused:
Enter Int: 5
5 Inserted in Root EMPTYException in thread "main" java.lang.NullPointerException
at BST.inOrder(BST.java:19)
at BSTDrive.main(BSTDrive.java:11)
So as you can see, the insertData method did run and I was able to get it to print the value for p (5) which is supposed to be root. Yet when it comes to the inOrderHelper method it's saying root is empty and jumps straight to print out "EMPTY"