This is part of a binary tree class, here is the find function, given the key to find the node in the tree, if not found return null, however this part have been recognized as dead code, when I move the if(current==null) statement to the bottom of inside while loop, it works, why? is it the same?
public class Tree {
public Node root;
public Node find(int key) {
Node current = root;
while (current.key != key) {
if (current == null) { //dead code here, why?
return null;
}
if (key < current.key) {
current = current.leftChild;
} else if (key > current.key) {
current = current.rightChild;
}
}
return current;
}
}
public class Node {
public char label;
public boolean visited = false;
public int key;
public float data;
public Node leftChild;
public Node rightChild;
}
If
currentisnullit will never reach to the null check as you are accessingcurrent.keybeforehand it will throw anullPointerExceptionIf you move theif(current==null)to bottom as you are assigning new value before it won't be a dead code. (as the current.leftChild andcurrent.rightChildmight benull)