Mark said:
yeah, I know java is pass-by-value, but there *must* be a way to do
something like this...
Must there, indeed? Perhaps you read too much Dr. Seuss
as a youngster:
"And it should be, it SHOULD be, it *SHOULD* be that way"
This is from "Horton Hatches the Egg," in which an elephant broods
on an abandoned bird egg, which then hatches into a tiny elephant
with wings. Nice tale for the kiddies, but if that's your sort
of reality, well, ...
private Node root = null;
public void insert(Comparable o)
{
insert(o,root);
}
private void insert(Comparable o, Node n)
{
if( n == null )
n = new Node(o);
else if( o.compareTo(n.o) < 0 )
insert(o,n.l);
else
insert(o,n.r);
}
basically.."root" never gets modified after calling something like
insert(5);
how do I fix this problem?
"This problem," I guess, is that the reference `n' is
passed by value, and nothing you do to that value propagates
back to the caller. What happens in Vegas stays in Vegas.
Consider that the call could have been insert(o, new Node())
or insert(o, fetchNodeFromDatabase()), and you'll see why
things are so.
So "this problem" cannot be "fixed." Your code, though
can be. One way is to introduce a class whose job is to hold
the Node reference:
class Nodule {
private Node node;
void setNode(Node node) {
this.node = node;
}
Node getNode() {
return node;
}
}
private Nodule rootHolder = new Nodule();
public void insert(Comparable o) {
insert(o, rootHolder);
}
private void insert(Comparable o, Nodule r) {
Node n = r.getNode();
if (n == null) {
r.setNode(new Node(o));
}
else if (o.compareTo(n.o) < 0)
insert(o, n.l);
else
insert(o, n.r);
}
Another way is to have the insert method return a reference
to the root of the tree, and make it the caller's responsibility
to assign the returned value to root:
private Node root;
public void insert(Comparable o) {
root = insert(o, root);
}
private Node insert(Comparable o, Node n) {
if (n == null)
n = new Node(o);
else if (o.compareTo(n.o) < 0)
insert(o, n.l);
else
insert(o, n.r);
return n;
}
Still another way -- and better than either of the above,
IMHO -- is to reconsider whether "null" is the right way to
represent an empty tree. See Knuth, volume I.