I am using three functions. Again, it is probably not efficient to do this, but I'm just trying to get something working here.
The following method MUST return a "value". It returns the value of the node to be removed, if it is found.
public V remove(int key) {
BNode<V> current = root;
BNode<V> currentNode = recursiveRemoveSearch(key,current);
System.out.println("In the remove method, the value is: " + currentNode);
return recursiveRemove(key, currentNode);
}
public BNode<V> recursiveRemoveSearch(int key, BNode<V> current)
{
System.out.print("val at start of recursiveRemoveSearch: " + current.getKey() + ". ");
if (key == current.getKey())
{
//current = current;
//current = root;
return current;
}
else if (key < current.getKey())
{
current = current.getLeft();
recursiveRemoveSearch(key, current);
}
else if(key > current.getKey())
{
current = current.getRight();
recursiveRemoveSearch(key, current);
}
return current;
}
public V recursiveRemove(int key, BNode<V> current)
{
//V value = current.getValue();
//if(current == null)
//{
//return null;
//}
System.out.print("Val at start of recursiveRemove " + current.getKey());
BNode<V> tempCurrent = current;
if(current.getLeft() == null && current.getRight() == null)
{
//value = current.getValue();
current = null;
return tempCurrent.getValue();
}
else if(current.hasLeft() == true || current.hasRight() == true)
{
if(current.hasLeft() == true)
{
BNode<V> currentChild;
currentChild = current.getLeft();
System.out.println(currentChild + "'s old Parent was: " + currentChild.getParent());
currentChild.setParent(current.getParent());
System.out.println(currentChild + "'s new Parent is: " + currentChild.getParent());
current = null;
return tempCurrent.getValue();
}
else if(current.hasRight() == true)
{
BNode<V> currentChild;
currentChild = current.getRight();
System.out.println(currentChild + "'s old Parent was: " + currentChild.getParent());
currentChild.setParent(current.getParent());
System.out.println(currentChild + "'s new Parent is: " + currentChild.getParent());
current = null;
return tempCurrent.getValue();
}
}
return tempCurrent.getValue();
}
Now what I want to happen so far (for the parts that I have coded) is when I go to remove a key (in my tests, key "8" in a tree of four nodes, 6 as the root, 4 on the left, and 7 on the right with 8 as its child)it should be able to find that key and reset the tree accordingly. HOWEVER, when I ran my tests, this is what happened.
val at start of recursiveRemoveSearch: 6.
val at start of recursiveRemoveSearch: 7.
val at start of recursiveRemoveSearch: 8.
In the remove method, the value is: 7:SEVEN
Val at start of recursiveRemove 7
In the highlighted red section, WHY HAS THE VALUE SUDDENLY CHANGED? It was fine, it should be returning 8....and yet, the recursiveRemove method now has the value 7...I need to get the node with value 8 to it.

New Topic/Question
Reply




MultiQuote






|