我正在尝试实现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
}
日食标记" else返回null;"行;作为死亡代码。我需要处理在树中找不到节点的情况,否则循环将永远运行,因此我需要类似的东西,这些东西在找不到节点时会返回null。
任何帮助都将受到赞赏:(
有一个查看这些行:
while(findkey != tempNode5.key){
if(tempNode5 != null){
如果tempNode5
为null,while
将抛出NullPointerException
,因此,任何后续行都不会执行。因此,如果tempNode5
不是null,则控制只会输入while
循环,使if..else
冗余。