Since black red tree is a binary search tree I have decided to use inheritance for implementation. Here is how in short node inheritance looks in my code:
struct BST_node
{
// public interface here
int key;
BST_node* left;
BST_node* right;
BST_node* parent;
};
struct BRT_node : BST_node
{
// public interface here
NodeColour colour;
};
Problem I have encountered with this is pointers in derived class are type of the base class. Therefore I cannot use them in context of derived class without explicit casting. Maybe hiding members and using virtual accesor methods could do the trick, but that would destroy this simple syntax:
node->left = node->parent;
Is there a better way of doing this?
What’s wrong with putting all the data members in
BRT_node?This way, you get to keep the “nice syntax” of
node->left = node->parent;.The problem with using inheritance here is because the red-black tree algorithms require
BRT_nodes, notBST_nodes. So inheritance in this case isn’t appropriate.