The root is always null.
This isn't homework, just trying to expand my knowledge. I'm attempting to recursively insert nodes into a Binary Tree. I've done some searching here but each implementation is so different, those changes aren't working.
This is my BinaryTree class:
public class BinaryTree {
static Node root;
public static void insertNode(int data){
if(root != null){
root.printData();
insertNew(root, new Node(data));
}else{
root = insertNew(root, new Node(data));
}
}
private static Node insertNew(Node current, Node n){
if(current == null){
return n;
}else if(current.data > n.data){
current.left = insertNew(current.left, n);
return current;
}else if(current.data < n.data){
current.right = insertNew(current.right, n);
return current;
}
return current;
}
public static void main(String[] args){
insertNode(9);
}
}
And this is my Node:
class Node {
int data;
Node left;
Node right;
Node(int data){
this.data = data;
}
public int printData(){
System.out.println(this.data);
return this.data;
}
}
Every time I run this, it assumes the root is null. I've got debug print lines in my working code so I can tell where I'm at in the methods. It hits that first if in the insertNew() function every time.
I'd like to understand conceptually where I'm failing.

roothas a value. Which is why it's killing me that it never does. After the first call toinsertNode(),rootshould always have a value.null. For example addinsertNode(10)to your main method. Java does not save values or data structures in-between runs.