为什么BST的findNode方法中的这一行被标记为"死代码"?

时间:2017-05-07 20:54:27

标签: java binary-search-tree dead-code

我正在尝试将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。

感谢任何帮助:)

1 个答案:

答案 0 :(得分:3)

看看这些内容:

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

如果tempNode5为空,while将抛出NullPointerException,因此,任何后续行都不会被执行。 因此,如果while不为空,则控件只会进入tempNode5循环,从而导致if..else多余。