A problem I'm solving is asking to insert a node inside a binary search tree, then return the root of the entire binary tree at the end.
The issue I seem to be having is saving the inserted node inside the original tree given it's root. My code is below:
static Node Insert(Node root,int value) {
insertAux(root, value);
return root;
}
static void insertAux(Node root, int value) {
if (root == null) {
root = new Node();
root.data = value;
root.left = root.right = null;
} else {
if (value > root.data) {
insertAux(root.right, value);
} else {
insertAux(root.left, value);
}
}
}
When I test this with the following tree:
4
/ \
2 7
/ \
1 3
it should result in:
4
/ \
2 7
/ \ /
1 3 6
I have tested this and my insertAux function does in fact assign root to a new Node() and the data for that node to the value 6 when it hits the null case at the end of the function. I have also tested and made sure that my Insert function returns the original root at the end of the entire call. However when I try to see if insertAux has assigned root.right.left to a new Node() and its data to 6 inside of the Insert function, I get a null pointer exception where root.right.left is null. Why is this, is my understanding of pointers or node assignment for Java wrong?