I'm having trouble trying to figure out the following. Imagine that I have the generic class Node<T> for representing the nodes of a binary tree, with some methods in it.
public class Node<T> {
T info;
Node<T> left;
Node<T> right;
public Node(T info) {this.info=info;}
//and some methods
}
Now I would like to add a method for Nodes of type Integer, which would sum all the nodes that can be reached from the current one:
public int sum(){
int sum = this.info;
if(this.left!=null) sum+=left.sum();
if(this.right!=null) sum+=right.sum();
return sum;
}
I am not quite sure how to do this. I thought of creating a class that extends Node<Integer> and adding the method sum there:
public class NodeOfIntegers extends Node<Integer>{
public NodeOfIntegers (T info) {super();}
public int sum(){...}
}
but since left and right are of type Node<Integer> and not NodeOfIntegers I can't do left.sum() and right.sum().
Is there a way to do this without redefining left and right?
Thank you very much.