Reputation: 15
Trying to make a root in this BST as such:
if (currentNode == null) {
currentNode = new BinaryNode(newInt);
System.out.println(currentNode);
System.out.println(newInt);
//System.out.println(newInt.getValue());
System.out.println("Node Null, made root");
}else{
The println is there for debugging. However I'm having issues as this is the output:
BinaryNode@7004ba66
4
Node Null, made root
BinaryNode@4669b7fe
6
Node Null, made root
BinaryNode@46aea8cf
1
Node Null, made root
BinaryNode@74ccd249
3
Node Null, made root
BinaryNode@3301f287
2
Node Null, made root
BinaryNode@44d9973a
8
Node Null, made root
BinaryNode@29578426
7
Node Null, made root
BinaryNode@30a4effe
5
Node Null, made root
BinaryNode@1c8825a5
9
Node Null, made root
Which makes me think it isn't recognising (currentNode == null) like it should. Any ideas why?
full pastebin: here
Any help greatly appreciated :)
Upvotes: 0
Views: 102
Reputation: 726489
The problem is that when you assign currentNode
, root
does not get assigned.
Java passes variables by value, meaning that a copy of the value or a reference gets passed into your method. In this case, currentNode
, a formal parameter of your insertNode
method, is passed a copy of the root
field returned by the getRoot
method.
To fix this, you should split the insertNode
method in two:
public void insert(int newInt);
and
private BinaryNode insert(int newInt, BinaryNode node);
The public method should be used without getRoot
parameter (the users of your class inserting in the tree should never need to pass the root, otherwise they would be able to break your tree by passing a node in the middle with numbers that should go in a different branch).
The private method should return the old or the new node. You should be using it like this:
public void insert(int newInt) {
root = insert(newInt, root);
}
The method itself should return new node if node
passed in is null
. When node
is not null, the method should return the node passed in.
As far as the outputList
problem goes, you should use StringBuffer
instead of String
to construct the output. Unlike String
which is immutable, StringBuilder
is mutable. It lets you change the string inside it (use append
instead of +=
).
Upvotes: 2
Reputation: 13177
You are not assigning to the root of your tree. Change it to:
if (root== null) {
root= new BinaryNode(newInt);
Upvotes: 1