title: Graph Theory, null pointer when trying to count nodes in tree
body: <pre><code>public class BuildTree {
  
      private HashMap&lt;Integer, LinkedList&lt;Integer&gt;&gt; tree;
      private int edges;
  
      public static void main(String[] args) {
          BuildTree bt = new BuildTree();
          bt.run();
      }
  
      private void run() {
          Scanner in = new Scanner(System.in);
          int n = in.nextInt();
          int m = in.nextInt();
          int treeRoot = 0;
          tree = new HashMap&lt;&gt;();
          edges = 0;
          for (int i = 0; i &lt; m; i++) {
              int adjacent = in.nextInt();
              int root = in.nextInt();
              if (i == 0) {
                  treeRoot = root;
              }
              if (!tree.containsKey(root)) {
                  tree.put(root, new LinkedList&lt;&gt;());
                  tree.get(root).add(adjacent);
              } else {
                  tree.get(root).add(adjacent);
              }
          }
  
  //        tree is built correctly
  //        tree.get(1).forEach(System.out::print);
  //        System.out.println();
  //        tree.get(2).forEach(System.out::print);
  //        System.out.println();
  //        tree.get(3).forEach(System.out::print);
  //        System.out.println();
  //        tree.get(6).forEach(System.out::print);
  //        System.out.println();
  //        tree.get(8).forEach(System.out::print);
  
          System.out.println(treeSize(2)); //expecting 3
      }
  
      private int treeSize(Integer i) {
          int size = 1;
          if (tree.get(i).isEmpty() || tree.get(i) == null) { //throws null pointer exception
              return size;
          } else {
              Iterator&lt;Integer&gt; it = tree.get(i).iterator();
              while (it.hasNext()) {
                  Integer subRoot = it.next();
                  size += treeSize(subRoot); //issue flagged here by console, directs to problematic if statement above
              }
          }
          return size;
      }
  }
  </code></pre>
  
  <p>The console input is the following:<br>
  10 9<br>
  2 1<br>
  3 1<br>
  4 3<br>
  5 2<br>
  6 1<br>
  7 2<br>
  8 6<br>
  9 8<br>
  10 8  </p>
  
  <p>I have already checked that the tree is built correctly by printing the LinkedList of adjacent integers for each node. My method for calculating tree size in reference to a certain root node keeps throwing a null pointer exception. I'm a novice regarding graph theory, and I'm not sure how to proceed.</p>