enter code here
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution 
{
    static boolean visited[];
    static int vertices;
    static boolean tree[][];
    public static void main(String[] args)
     {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner sc=new Scanner(System.in);
        vertices=sc.nextInt();
        int edges=sc.nextInt();
        visited=new boolean[vertices+1];
        boolean tree[][]=new boolean[vertices+1][vertices+1];
        for (int k=0;k<vertices+1 ;k++ ) 
        {
            for (int j=0;j<vertices+1 ;j++ )
            {
                tree[k][j]=false;
            } 
        }
        int count[]=new int[vertices+1];
        //Arrays.fill(count,1);
        for(int i=0;i<edges;i++)
            {
            int u=sc.nextInt();
            int v=sc.nextInt();
            tree[v][u]=true;
        }
        for (int i=0;i<vertices+1 ;i++ ) 
        {
            count[i]=bfs(i) + 1;             //getting error at this line
        }
        int finalcount=0;
        for (int i=0;i<vertices+1 ;i++ ) 
        {
            if (count[i]%2==0) 
            {
                finalcount++;
            }
        }
        System.out.println(finalcount);
    }
  public static int bfs(int node)
      {
      Queue<Integer> q=new LinkedList<Integer>();
      for(int i=0;i<vertices+1;i++)
          {
          visited[i]=false;
      }
      visited[0]=true;
      int counter=0;
      q.add(node);
      while( !q.isEmpty() )
      {
         int nextNode;                // Next node to visit
         int i;
         nextNode = Integer.valueOf(q.remove());
         if ( ! visited[nextNode] )
         {
            visited[nextNode] = true;    //mark visited
            for ( i = 0; i < vertices+1; i++ )
             {  
                if ( tree[nextNode][i] && ! visited[i] ) //getting error at this line too
                {  
                    q.add(i);
                    counter++;
                }
             }
         }
      }
      return counter;
  }
}
/*
10 9
2 1
3 1
4 3
5 2
6 1
7 2
8 6
9 8
10 8
ans:2
20 19
2 1
3 1
4 3
5 2
6 5
7 1
8 1
9 2
10 7
11 10
12 3
13 7
14 8
15 12
16 6
17 6
18 10
19 1
20 8
ans:4
*/
I am getting nullpointerexception. I have commented the line where the error is occurring. Please Help!
This is the solution for even tree problem on hackerrrank... I know the logic but getting this error.
 
    