我正在尝试将findNode方法实现为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标记行&#34;否则返回null;&#34;作为死代码。我需要处理在树中找不到节点的情况,否则while循环将永远运行,所以我需要类似的东西,当找不到节点时将返回null。
感谢任何帮助:)
答案 0 :(得分:3)
看看这些内容:
while(findkey != tempNode5.key){
if(tempNode5 != null){
如果tempNode5
为空,while
将抛出NullPointerException
,因此,任何后续行都不会被执行。
因此,如果while
不为空,则控件只会进入tempNode5
循环,从而导致if..else
多余。