I am trying to insert element in Binary Search Tree with iterative method but i am getting NullPointerException and i am not able to figure out why this error is getting. I tried changing the loop and checking the temp but i didnt get what is happening wrong there. EDIT:- I have added the whole Code.
     import java.util.*;
  import java.io.*;
  class Node {
      Node left;
      Node right;
      int data;
      Node(int data) {
          this.data = data;
          left = null;
          right = null;
      }
  }
  class Solution {
      public static void preOrder(Node root) {
          if (root == null)
              return;
          System.out.print(root.data + " ");
          preOrder(root.left);
          preOrder(root.right);
      }
      /* Node is defined as :
      class Node 
         int data;
         Node left;
         Node right;
         */
      public static Node insert(Node root, int data) {
          Node inserter = new Node(data);
          Node temp = root;
          while (true) {
              if (inserter.data <= temp.data) {
                  if (temp.left == null) {
                      temp.left = inserter;
                      break;
                  } else
                      temp = temp.left;
              } else {
                  if (temp.right == null) {
                      temp.right = inserter;
                      break;
                  } else
                      temp = temp.right;
              }
          }
          return root;
      }
      public static void main(String[] args) {
          Scanner scan = new Scanner(System.in);
          int t = scan.nextInt();
          Node root = null;
          while (t-- > 0) {
              int data = scan.nextInt();
              root = insert(root, data);
          }
          scan.close();
          preOrder(root);
      }
  }
 
     
    