我在这里使用二叉树结构。我从包含 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
的唯一原因是当 currNode
为 null
时。我怀疑 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/