In tree
class there is a method called arrange()
. When I print any node value within the arrange()
method the value comes to be accurate, but when I use the method print()
in tree
class I get a NullPointerException
. Please help!
public class Node {
Node lnode;
Node rnode;
int data;
public Node(String d) {
data = Integer.parseInt(d);
this.rnode = null;
this.lnode = null;
}
}
public class tree {
public void arrange(String s[], int n, Node r) {
Node root = new Node(s[0]);
for (int i = 1; i < n; i++) {
r = root;
if (Integer.parseInt(s[i]) > root.data && root.rnode == null) {
root.rnode = new Node(s[i]);
} else if (Integer.parseInt(s[i]) < root.data && root.lnode == null)
root.lnode = new Node(s[i]);
while (!(r.rnode == null) && (Integer.parseInt(s[i])) > r.data) {
r = r.rnode;
if (Integer.parseInt(s[i]) > r.data && r.rnode == null)
r.rnode = new Node(s[i]);
else if (Integer.parseInt(s[i]) < r.data && r.lnode == null)
r.lnode = new Node(s[i]);
}
while (!(r.lnode == null) && (Integer.parseInt(s[i])) < r.data) {
r = r.lnode;
if (Integer.parseInt(s[i]) > r.data && r.rnode == null)
r.rnode = new Node(s[i]);
else if (Integer.parseInt(s[i]) < r.data && r.lnode == null)
r.lnode = new Node(s[i]);
}
}
System.out.println(root.rnode.data);
}
public void print(Node r) {
System.out.println(r.rnode.data);
}
}
Main method:
Node root;
int n;
System.out.println("Enter the number of elements you want to enter into the bst: ");
Scanner sc = new Scanner(System.in);
n = Integer.parseInt(sc.nextLine());
System.out.println("Enter the elements you want to enter into the bst: ");
Scanner s = new Scanner(System.in);
String st[] = new String[n];
st = s.nextLine().split(" ");
root = new Node(st[0]);
tree t = new tree();
t.arrange(st, n, root);
t.print(root);