Reputation: 4249
I am trying to write a function that searches for a value on a tree I built, I have written a recursive function that works fine. Now I want to improve my running time, so I want to use while loop to look for the value. The problem is that I'm getting NullPointerException
. I know for sure that the tree is ok, because before I perform the search I print all the values. So what's the problem with my code?
public void SearchByLoop(Node root,final int val){
while(root != null || root.getVal() == val){
if(root.getVal() < val)
root = root.getRightChild();
else if(root.getVal() > val)
root = root.getLeftChild();
}
if(root == null)
System.out.println("Couldn't find value " + val);
else if(root.getVal() == val)
System.out.println("Found value " + val);
}
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Tree theTree = new Tree();
Random rand = new Random();//Create random variable.
int val = 0;
for(int i = 0 ; i < 100; i ++){
val = rand.nextInt(151) + (0);
theTree.addNode(val,"a");
}
theTree.inOrderTraverseTree(theTree.getRoot());
theTree.SearchByLoop(theTree.getRoot(), 10);
}
}
Now, the inOrderTraverse
method prints all of the values, so I know that the tree is ok. What can be the problem? Thank you!
Upvotes: 0
Views: 5259
Reputation: 393811
This condition
while(root != null || root.getVal() == val)
will give you a NullPointerException when root
is null.
You probably want
while(root != null && root.getVal() != val)
Upvotes: 3