thunderousNinja thunderousNinja - 8 months ago 34
Java Question

inserting nodes into a binary tree in java question

im coming from c++ to java and i am confused on binary trees with java. is the only way to have a Node class is to make it an inner static class? all the examples i see do this. However, the way im doing it is i have a node class and a binarytree class uses this node class. but i keep getting an error when i try inserting into the tree after the second insert. i get an exception at this line

if(dataIn <= nodeIn.getLeft().getData()){


I am confused as to what i did wrong.... here is my code for insert that i have. thanks in advance..

public void insert(int dataIn){
root = insert(root, dataIn);
}

private Node insert(Node nodeIn, int dataIn){
if(nodeIn==null){
nodeIn = new Node(null, null, dataIn);
}else{
if(dataIn <= nodeIn.getLeft().getData()){
nodeIn.setLeft(insert(nodeIn.getLeft(), dataIn));
}else{
nodeIn.setRight(insert(nodeIn.getRight(), dataIn));
}
}

return nodeIn;
}

Answer Source

You need to test whether nodeIn.getLeft() == null.