Java递归二叉树方法的空指针异常

标签 java recursion nullpointerexception binary-tree

这个方法给了我一个空指针异常,我不知道为什么会这样。递归代码有问题吗?

 public void clearAllSelections(){
    //Recursively clear all the selections in the sub-tree of this node
    //basis:
    isSelected = false;
    if(isLeaf()) return;

    //recursion:
    childrenRight.clearAllSelections();
    childrenLeft.clearAllSelections();

}

最佳答案

您的 isLeaf() 检查不够,因为二叉树中的节点可能只有一个子节点,因此您必须添加空检查:

public void clearAllSelections(){
    //Recursively clear all the selections in the sub-tree of this node
    //basis:
    isSelected = false;
    if(isLeaf()) return;

    //recursion:
    if (childrenRight != null)
        childrenRight.clearAllSelections();
    if (childrenLeft != null)
        childrenLeft.clearAllSelections();

}

关于Java递归二叉树方法的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33281797/

相关文章:

java - 禁用 Bean 定义覆盖 Spring Boot Web 应用程序(war 文件)

java - 金额存储在哪里?

entity-framework - GraphDiff 和 EF6.1 – 递归多对多关系

java - 如何使用realm.io(Java/Android)递归删除记录?

java - 为什么Java编译器允许通过空对象访问静态变量?

Java : to avoid NullPointer , 初始化了一个字符串数组

java - 配置文件位于 JAR 内。如何将配置文件放在JAR之外?

java - 只允许正数或空格

java - 奇怪的 nullPointerException 错误 - 数据库相关

java - 有哪些免费工具可用于分析 java 中的锁争用?