I'm trying to implement a Red-Black Tree that inherits from a BS Tree. BST
uses BSNode
as its nodes while RBT
(Red-Black Tree) uses RBNode
which in turn inherits from BSNode
. The code looks like this, the problems arise in the code:
#include <iostream>
#define _BST BST<K, T, RBNode<K, T>>
// attempt 1
//template <typename K, typename T, typename NODE>
//class BSNode
//{
//
//public:
//
// K key;
// T value;
//
// NODE* left;
// NODE* right;
//
// // ...
//};
// attempt 2
template <typename K, typename T, template<typename, typename> typename NODE>
class BSNode
{
public:
K key;
T value;
NODE<K, T>* left;
NODE<K, T>* right;
// ...
};
template <typename K, typename T>
class RBNode : public BSNode<K, T, RBNode>
{
public:
bool color;
// ...
};
template <typename K, typename T, typename NODE>
class BST
{
public:
NODE* root = nullptr;
// ...
};
template <typename K, typename T>
class RBT : public _BST
{
// ...
};
int main()
{
RBT<int, int> rbt;
// attempt 1
// recursive and can't be done.
// BST<int, int, BSNode<int, int, BSNode<int, int, BSNode<int.....
// attempt 2
// template arguments list for NODE takes
// 2 arguments while BSNode takes 3. Not compatible.
// BST<int, int, BSNode<int, int, BSNode>>
}
questions:
1 -
how to implement it so that BST
s are just written as BST<int, int>
while still having it accept different types of nodes for left and right such as RBNode
?
2 -
how to let RBNode
inherit from BSNode
while being able to create BSTs and RBT
s?
3 -
in attempt 2, in the macro #define _BST BST<K, T, RBNode<K, T>>
, why do I get an error when writing it as #define _BST BST<K, T, RBNode>
? in the class BSNode
, left and right are defined
as NODE<K, T>*
. this means substituting NODE
by BSNode<K, T>
would result in left and
right being equal to BSNode<K, T><K, T>*
. why is this the right way?
Is there something wrong with the design or if can it be improved?