Reputation: 43
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);
}
}
Upvotes: 1
Views: 153
Reputation: 575
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);
}
In main method you are passing root == null
You need to rewrite your insert method then it will work
public static Node insert(Node root, int data) {
// check if root == null then initialize root and return it
if(root == null){
return new Node(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;
}
Upvotes: 1
Reputation: 1313
Your issue is in your main method:
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);
}
You initialize Node root = null
, and the first time you enter your while loop, root will still be null when passing it to the insert method: root = insert(root, data);
public static Node insert(Node root, int data) {
Node inserter = new Node(data);
Node temp = root;
while (true) {
if (inserter.data <= temp.data) {
...
So the first time you enter the insert method, temp will be set to null, giving a nullpointer on the temp.data
in the if (inserter.data <= temp.data)
line.
Upvotes: 0