Part of the reason it's confusing is that "Node" should not be a parameter to the insert method, you should be calling an insert method defined in node.
So let's say you hold the "Root" node in your "normal code"--let's call it "rootNode" just to be obscure.
Okay, so your code to insert into the tree would be:
rootNode.insert(newValue);
Easy enough.
Now to define that method.
public class Node {
private int value;
private Node lower;
private Node higher;
public void insert(int newValue) {
if (newValue < value)
if(lower == null)
lower=new Node(value);
else
lower.insert(newValue);
else
if(higher == null)
higher=new Node(value);
else
higher.insert(newValue);
}
// and you'll need a constructor
public Node(int value) {
this.value=value;
}
}
This should read much more clearly. I'm going to hit "Post" then I'm going to edit it and figure out how to easily refractor that evil evil copy & paste code.
On second thought, I'll leave it there because it's more readable. The best fix I can see is to make the nodes an array, then you get:
public class Node {
private int value;
private Node[] nodes=new Node[2];
private final int LOWER=0;
private final int HIGHER=1;
public void insert(int newValue) {
int index=LOWER;
if (newValue > value)
index=HIGHER;
if(nodes[index] == null)
nodes[index]=new Node(value);
else
nodes[index].insert(newValue);
}
}
But I won't replace the original because, as I said, it's clearer.
I recommend the refactoring book for more of this. It really does help simplify your code once you really get OO. Passing an object to an otherwise static method (one that doesn't use member variables) is a dead give-away.
With more considerations about @ted's comment and OO--getLeft and getRight shouldn't even be an issue. Neither is necessary outside the abstraction.
In general what you probably need is these methods in Node:
public boolean doesContain(int value) {
if(value == this.value)
return true
else
return nodes[ this.value < value ? LOWER : HIGHER].doesContain(value);
}
and maybe
public void getValuesSorted(LinkedList l) {
nodes[LOWER].getValuesSorted(l);
l.put(value);
nodes[HIGHER].getValuesSorted(l);
}
Then you don't even need to expose that it's a tree you are dealing with--beter OO abstraction.