gpt4 book ai didi

java - 使用二叉树节点的 while 循环中出现 NullPointerException

转载 作者:行者123 更新时间:2023-12-02 05:33:53 25 4
gpt4 key购买 nike

我在这里使用二叉树结构。我从包含 while 语句的行收到“NullPointerException”。我完全不明白为什么会这样。

   BinaryTreeNode<CharData> currNode = theTree.findValue(data);

// Move up the Binary Tree to create code.
while(currNode.getParent() != null) {
// The loop does some stuff that doesn't
// affect what is assigned to currNode.

// Move to the parent node for the next iteration.
currNode = currNode.getParent();

} // End the while loop.

return code; // Return the string of binary code.

Find value 是 BinaryTree 类中的一个方法,用于搜索并查找包含特定数据的节点。我知道这是通过在该实现之外单独测试它来实现的。

最佳答案

while 循环语句抛出 NPE 的唯一原因是当 currNodenull 时。我怀疑 findValue() 返回了 null

我猜一个修复(当你关心最顶层的节点时)是:

while(currentNode != null) {
rootNode = currentNode;
currentNode = currentNode.getParent();
}

或者依赖于 boolean 快捷方式评估的典型模式:

while(curentNode != null && currentNode.getParent() != null) 

或者我更喜欢使用守卫的解决方案:

if (currentNode == null)
throw NotFound(); // or return something

while(curentNode.getParent() != null) {

关于java - 使用二叉树节点的 while 循环中出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25214701/

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