I have implemented a simple Binary Search Tree. I want to create a subclass Red-Black Tree, but I'm having problems. The code for the BST is as follows, with the irrelevant details removed. The BST works perfectly fine.
Node:
public Node {
private int key;
public Node left;
public Node right;
public Node parent;
public Node(int key){
// init
}
}
BST:
public BinarySearchTree {
protected Node root;
public void insert(int key){
Node insertNode = new Node(key); // This is problematic
// perform insertion
}
}
I need to subclass Node to add a color property:
RbtNode:
public RbtNode extends Node {
private boolean isBlack;
public RbtNode(int key){
// init
}
}
And the RedBlackTree class
RedBlackTree
public RedBlackTree {
public void insert(int key){
super.insert(key);
// perform RBT fixes
}
}
As you can see, I want to reuse the insert method of BinarySearchTree, but since it inserts a Node and not an RbtNode, it won't work.
A solution I came up with is to create a separate method createNode(int key) that I can override, but I would need to do quite a bit of typecasting when accessing/manipulating nodes on the subclass.
Is there any cleaner solution, preferrably one without typecasts?
EDIT: The problem is when calling super.insert from the subclass (RedBlackTree), it uses the parent's root field instead of the subclass's root field.