gpt4 book ai didi

java - 为什么 BST 的 findNode 方法中的这一行被标记为 "dead code"?

转载 作者:行者123 更新时间:2023-12-01 20:26:26 27 4
gpt4 key购买 nike

我正在尝试实现 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 标记了“else return null;”行作为死代码。我需要处理在树中找不到节点的情况,否则 while 循环将永远运行,所以我需要类似的东西,当找不到节点时返回 null。

感谢任何帮助:)

最佳答案

看看这些行:

while(findkey != tempNode5.key){
if(tempNode5 != null){

如果 tempNode5 为 null,while 将抛出 NullPointerException,因此,任何后续行都不会被执行。因此,如果 tempNode5 不为 null,控制只会进入 while 循环,从而使 if..else 变得多余。

关于java - 为什么 BST 的 findNode 方法中的这一行被标记为 "dead code"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43836623/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com