I am attempting to implement a findNode method as part of a binary search tree in java.
public Node findNode(int findkey){
Node tempNode5 = root;
while(findkey != tempNode5.key){
if(tempNode5 != null){ // if the tempNode5 is not null
// and the node to be found hasn't been found yet
// then we will go to the leftChild or rightChild
// depending on the key
if(findkey < tempNode5.key){
tempNode5 = tempNode5.leftChild;
}
else tempNode5 = tempNode5.rightChild;
}
else return null; // this is the line that Eclipse marks "dead code"
// if the tempNode5 reaches null, it means the node to be found
// was not found in the BST, in which case I want to return null
}
return tempNode5; // if the while loop has exited and reached this line it means that
// the node *has* been found, so I want to return it
}
Eclipse marks the line "else return null;" as dead code. I need to deal with the case that the node is not found in the tree, otherwise the while loop will run forever, so I need something similar that will return null when the node is not found.
Any help is appreciated :)
Have a look at these lines:
while(findkey != tempNode5.key){
if(tempNode5 != null){
If tempNode5
is null, while
will throw a NullPointerException
and hence, any subsequent line won't be executed.
So, control will only enter the while
loop if tempNode5
is not null, making if..else
redundant.