I tried to write a recursive function for adding Nodes into a Binary Tree.
The Problem is that although the root has a new value after inserting the first element
(confirmed by System.out.println() ), it´s still null when I try to get the root value in the main through System.out.println();
package polo;
public class BTNode {
public int value;
public BTNode left;
public BTNode right;
BTNode(int value){
this.value = value;
left = null;
right = null;
}
}
package polo;
public class Tree {
public BTNode root;
public Tree() {
root = null;
}
public void add(int i, BTNode n) {
if (n == null) {
n = new BTNode(i);
System.out.println("New root value : " + n.value);
} else {
if (i < n.value) {
if (n.left == null) {
n.left = new BTNode(i);
} else {
add(i, n.left);
}
} else { // i >= n.value
if (n.right == null) {
n.right = new BTNode(i);
} else {
add(i, n.right);
}
}
}
}
public static void main(String[] args) {
Tree t = new Tree();
t.add(3, t.root);
System.out.println(t.root.value);
}
}
The command line output is :
New root value : 3
Exception in thread "main" java.lang.NullPointerException at polo.Tree.main(Tree.java:57)
(Line 57 is where System.out.println(t.root.value); stands)