I have a superclass and a subclass as follows:
class Tree{
..
public void add(..){
//makes a call to protected function add(..)
}//for client to use.
protected TreeNode add(..){}//recursive function which calls itslef
}
class Stree extends Tree{
//overrides the recursive add function from class Tree
protected TreeNode add(..){
..
super.add();//calls the non-recursive add function in superclass.
}
}
The problem here is that when I call super.add() from the new add function in the subclass, it goes to Tree.add(). Inside Tree.add(). there is a call to add(), which calls the recursive add function in the subclass instead of super, i.e. Stree.add(), instead of Tree.add() which results in an infinite loop. Do you guys see where the problem is?
This is a homework assignment hence I cannot change the name of the recursive function. I am explicitly required to add functionality to the recursive add function, without rewriting any existing code, which basically means I will have to make a call to the original add() function.
edit: Code for the Tree.add()//recursive. Note that I cannot modify this code to gain the functionality I seek.
protected StreeNode add(StreeNode node, String value) {
if (node == null) {
node = new StreeNode(value);
numElements++;
} else if (node.data.compareTo(value) == 0) {
// do nothing, String was already in Set
} else if (node.data.compareTo(value) > 0) {
node.left = add(node.left, value); // x = change(x)
} else {
node.right = add(node.right, value); // x = change(x)
}
return node;
}
edit: Now that I see that this is the expected behaviour, how do I go about achieving the following:
- Add the value using the original recursive
add() - Implement extra functionality
Without seeing the parameters I assume
void add(...)is the method to add something into the tree, whereas the protected recursive method looks for the node to add to and then performs the add.I further assume the public non-recursive method passes the tree’s root to the recursive method as a start parameter while the recursive method either passes the left or right child until you hit a leaf. Calling the non-recursive method might thus in starting at the root again and again.
Thus I’d say that the recursive and inherited method should not call the non-recursive version but should call itself again.