If I have a node class(es) that can accept a generic type for it’s key value:
class Node<K extends Comparable<K>> implements Comparable<Node<K> {
...
}
class KeyValueNode<K extends Comparable<K>, V> extends Node<K> {
...
}
Is it possible to declare a generic binary tree class that accepts a generic type of node, which can contain a generic type of key value? I thought it would look something like this….
class BinaryTree<N<K>> {
N<K> root;
BinaryTree<N<K>> left, right;
...
}
Apologies for any glaring misunderstandings, I’m still trying to get the hang of generics and the syntax in Java, would greatly appreciate any help or insights.
Thanks!
A binary tree structure will essentially just hold a reference to the root node. So it should have the same type parameters as its nodes:
Or for the key-value design:
Note that it’s debatable whether an enclosing tree class is necessary, since it’s the nodes that are pointing to each other.