重复二叉树方法上的Java空指针异常

时间:2015-10-22 13:07:21

标签: 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();

}

2 个答案:

答案 0 :(得分:3)

您的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();

}

答案 1 :(得分:2)

在进行函数调用之前对childrenRight和childrenLeft进行空检查