I'm new to Java, I want to create a Binary Search Tree class with insertion and preorder traversal, but when I finish the insertion the root object remains null and the compiler throws NullPointerException during the preorder traversal.
My node class:
class Node {
int info;
Node left;
Node right;
public Node() {
info = 0;
left = null;
right = null;
}
Node(int x) {
info = x;
left = null;
right = null;
}
}
My Binary Search Tree class:
public class BinarySearchTree {
private Node root;
public BinarySearchTree() {
root = null;
}
private void insertPrivate(Node node, int x) {
if(node == null) {
node = new Node(x);
}
else {
if(x < node.info) {
insertPrivate(node.left, x);
}
else if (x > node.info) {
insertPrivate(node.right, x);
}
}
}
public void insert(int x) {
insertPrivate(root, x);
}
private void preorderPrivate(Node node) {
if(node != null) {
System.out.println(node.info);
preorderPrivate(node.left);
preorderPrivate(node.right);
}
}
public void preorder() {
preorderPrivate(root);
}
public static void main(String[] args) {
BinarySearchTree t = new BinarySearchTree();
t.insert(12);
t.insert(13);
t.preorder();
}
}
The issue is a misunderstanding of Java referencing as seen with this section of code.
Java references are passed by value into function arguments.
Let me give you an example to clarify.
You are going to have to restructure your program. One way would be to have
insertPrivate
return aNode
and assign that value to root. It is not the most efficient but it will work.