While solving a mindless task, a question came to my mind:
/**
* Find element by key in binary tree.
*/
public E find(K key) {
BinaryTreeNode<K, E> node = this.root;
while (node != null) {
if (node.getKey().compareTo(key) > 0) { //element in tree too big
node = node.getLeft();
} else if (node.getKey().compareTo(key) < 0) { //element in tree too small
node = node.getRight();
} else { //found element
return node.getElement();
}
}
return null;
}
In the while
block, only one if
statement can be true. So the while
block could be written using continue
instead of else if
:
while (node != null) {
if (node.getKey().compareTo(key) > 0) { //element in tree too big
node = node.getLeft();
continue;
}
if (node.getKey().compareTo(key) < 0) { //element in tree too small
node = node.getRight();
continue;
}
//found element
return node.getElement();
}
Is there any difference in performance between the two methods?