Reputation: 663
I am trying to write a binary tree and the add method is continually overwriting the root of the tree. I have two methods a recursive add method that takes in a String and a Node and then a regular add method that simply calls the recursive method. Any help would be greatly appreciated.
public Node recAdd(String event , Node tNode ){
//tNode -> tree node
if (tNode == null){
// Addition place found
root = new Node(event);
System.out.println("added root");
}
else if (tNode.event.compareTo(event) <= 0){
tNode.setLeft(recAdd(event, tNode.getLeft()));
// System.out.println("added left");// Add in left subtree
}
else{
tNode.setRight(recAdd(event, tNode.getRight()));
// System.out.println("added right");
}// Add in right subtree
return tNode;
}
//////////////////////////////////////////////
public void add(String event){
if(root != null){
System.out.println("The root currently is " + root.event );
}
recAdd(event , root);
}
And my node class is as follows
public class Node {
Node left;
Node right;
String event;
Node(String event){
this.event = event;
this.left = null;
this.right = null;
}
public void setEvent(String event){
this.event = event;
}
public void setLeft(Node left){
this.left = left;
}
public void setRight(Node right){
this.right = right;
}
public String getEvent(){
return event;
}
public Node getLeft(){
return left;
}
public Node getRight(){
return right;
}
}
Upvotes: 0
Views: 2797
Reputation: 3302
What's happening is that you recursively search through the tree until you reach a node that hasn't been assigned yet (i.e., it is null
). At this point, you are overwriting root rather than creating the new node.
For example:
root
/ \
node null <- You want to assign this node, not overwrite root
/ \
null null
To do this:
public Node recAdd(String event , Node tNode ){
if (tNode == null){
tNode = new Node(event); // <--- Don't overwrite root
}
else if (tNode.event.compareTo(event) <= 0){
tNode.setLeft(recAdd(event, tNode.getLeft()));
}
else{
tNode.setRight(recAdd(event, tNode.getRight()));
}
return tNode;
}
You would also need to modify your add()
function:
public void add(String event){
root = recAdd(event , root); // <-----Reassign root
}
Upvotes: 0
Reputation: 6043
You are replacing the root node whenever you find a spot to insert the current node:
public Node recAdd(String event, Node tNode) {
//tNode -> tree node
if (tNode == null) {
// Addition place found
root = new Node(event); // Problem is RIGHT HERE
System.out.println("added root");
}
//...
}
Upvotes: 1