Pregunta

Im working on a right rotate method for a splay tree. I keep getting a null pointer exception when I try to run my program but im not sure why. This is my tree

      5
     /
    2
   /
  1

this is where i get the null pointer, its on the lr assignment. lr should be null because 2 doesnt have a right but shouldnt the node just be null and then the program should keep going? or since its null I have to check first if 2 will have a right?

    Node<E> p = findParent(x.getData());    
    Node<E> l = x.getLeft();
    Node<E> lr = l.getRight();
¿Fue útil?

Solución

If l is null, then l.getRight() will throw a null pointer exception.

You need to test whether l is null:

Node<E> lr = (l==null)?null:l.getRight();

That code will assign null to lr if l is null, and will assign l.getRight() if l is not null.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top