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
  • 5,489
  • 46
  • 45
  • 50
Ben Joshua S
  • 87
  • 1
  • 9

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
  • 387,369
  • 54
  • 702
  • 768
2

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

AbtPst
  • 7,778
  • 17
  • 91
  • 172