0

this method is giving me a null pointer exception and I don't know why that is. Is there something wrong with the recursion code?

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

}
karel
  • 4,637
  • 41
  • 42
  • 47

2 Answers2

3

Your isLeaf() check is not sufficient, since a node in a binary tree may have a single child, so you must add null checks :

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

}
Eran
  • 374,785
  • 51
  • 663
  • 734
2

do a null check on childrenRight and childrenLeft before making the function call

AbtPst
  • 7,292
  • 14
  • 78
  • 160