Reputation: 509
This is my code
public boolean insertWord(String key, String meaning) {
if((root == null) ){
root = new TreeNode();
root.key = key;
root.meaning = meaning;
}
else{
TreeNode subroot = root;
if(subroot.key.compareTo(key) == 0){
return false;
}
else if(key.compareTo(subroot.key) < 0){
if(subroot.left != null){
subroot = root.left;
return insertWord(key, meaning);
}
else{
subroot.left = new TreeNode();
subroot.left.key = key;
subroot.left.meaning = meaning;
}
}
else{
if(subroot.right != null){
subroot = root.right;
return insertWord(key, meaning);
}
else{
subroot.right = new TreeNode();
subroot.right.key = key;
subroot.right.meaning = meaning;
}
}
}
return true;
}
Doing this gives me stackoverflow error. Can someone please help me understand why I keep getting that error. I know its because of an infinite loop but I dont know why its happening. Can someone tell me where it is happening and how to fix it? Thanks
Upvotes: 3
Views: 447
Reputation: 24157
As Aaron has pointed out you need to update the new key to which you will compare next. In your code if left node is null you inserted the node but if it is not null then you need to compare your key with the key of this new node. Where is this code?
else if(key.compareTo(subroot.key) < 0){
if(subroot.left != null){
subroot = root.left;
// WHERE ARE YOU USING KEY OF THIS NEW NODE subroot FOR COMPARISON?
return insertWord(key, meaning);
}
else{
subroot.left = new TreeNode();
subroot.left.key = key;
subroot.left.meaning = meaning;
}
}
Edit: The implementation for methods to insert left and right should be something similar:
private void insertNodeToLeft(Node<T> parent, Node<T> child) {
// New left node
parent.setLeft(child);
child.setParent(parent);
size++;
}
private void insertNodeToRight(Node<T> parent, Node<T> child) {
// New right node
parent.setRight(child);
child.setParent(parent);
size++;
}
Upvotes: 1
Reputation:
In the below code if subroot
is set as root.left
then shouldn't you use the key of subroot
further? Where are you passing that information?
if(subroot.left != null){
subroot = root.left;
return insertWord(key, meaning);
}
Now I am presenting my version which I have implemented:
protected Node<T> insertValue(T value) {
Node<T> newNode = getNewNode(value);
// If root is null, assign
if (root == null) {
root = newNode;
size++;
return newNode;
}
Node<T> currentNode = root;
while (currentNode != null) {
if (newNode.getData().compareTo(currentNode.getData()) <= 0) { // Less than or equal to goes left
if(currentNode.getLeft() == null) {
insertNodeToLeft(currentNode, newNode);
break;
}
currentNode = currentNode.getLeft();
} else { // Greater than goes right
if (currentNode.getRight() == null) {
insertNodeToRight(currentNode, newNode);
break;
}
currentNode = currentNode.getRight();
}
}
return newNode;
}
Hope it will help you.
Upvotes: 2