-1

I am trying to print no of node values in a given range in an avl tree .But when I try to run the program I get NullPointerException. I couldn't get much help from previous questions of same topic.How can i correct it here.Here's my code of that portion:

public void range(int low, int up){
    if(low >up){
        System.out.println("Illegal input");
    }

    if(this.root != null){
        System.out.println(rangeS(this.root,low,up) +"");
    }

}

public static int rangeS(AvlNode root,int k1 ,int k2){
    int c = 0;
    if(root.key >= k1 && root.key <= k2){
        c = c+1;
    }
    if(root.key > k1 ){
        rangeS(root.left,k1,k2);
    }

    if(root.key <k2){
        rangeS(root.right,k1,k2);
    }
    return c;
}
fabian
  • 80,457
  • 12
  • 86
  • 114
user2944059
  • 23
  • 1
  • 5

1 Answers1

0

Since you are calling rangeS recursivly,root.left or/and root.right may be null. This will result in a NPE when root.key is accessed. Chech for null and return 0 prior to call rangeS.

public static int rangeS(AvlNode root,int k1 ,int k2){

  if(root == null) {
     return 0;
  }
  ...
}

Update:

To count the number of vertices under the tree, add the result of rangeS to your counter c, e.g. c += rangeS(...).

Hannes
  • 2,018
  • 25
  • 32