I have a Java task where I have to create a splay tree which requires me to find the parent and grandparent node of the node I am accessing. To do this, I've chosen to create a findParent method. Here is my Node class.
public class Node<T>
{
public T elem = null;
public Node<T> left = null;
public Node<T> right = null;
public Node(T elem) {
this.elem = elem;
}
public String toString() {
String out = elem.toString();
out += " [L: "+ (left == null ? "null" : left.elem) + "] ";
out += " [R: "+ (right == null ? "null" : right.elem) + "] ";
return out;
}
}
I am not allowed to change the Node class. My SplayTree class is made up of these nodes and inside the SplayTree class, I have my findParent function.
public Node<T> findParent(Node<T> A) {
Node<T> P = root;
if (P.left == A || P.right == A) {
return P;
} else if (A.elem.compareTo(P.elem) < 0) {
P = P.left;
} else {
P = P.right;
}
return null;
}
To test the code, I've entered the following numbers in order into the tree "50, 25, 100, 5, 110, 115, 75, 42, 101, 112". The insert method follows the normal BST insert rules of having larger elements on the right and smaller elements on the left. I tested my findParent method using the node containing 110 as the target so theoretically, it should return 100 as the parent and to get the grandparent, I would use findParent(parent) which should return 50 but instead, I get a nullptr exception. I've tested my insert function to see if I am populating my tree correctly, however, that is not the case as the insert method works correctly.