将BST继承到黑红树的问题

时间:2011-03-05 16:39:26

标签: c++

由于黑红树是二叉搜索树,我决定使用继承来实现。以下是我的代码中短节点继承的外观:

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;
};

我遇到的问题是派生类中的指针是基类的类型。因此,如果没有显式转换,我不能在派生类的上下文中使用它们。也许隐藏成员并使用虚拟访问器方法可以解决这个问题,但这会破坏这种简单的语法:

node-> left = node-> parent;

有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

将所有数据成员放入BRT_node

有什么问题
struct BRT_node
{
    int key;
    BRT_node* next;
    BRT_node* prev;
    BRT_node* parent;
    NodeColour colour;
};

这样,你就可以保持node->left = node->parent;的“漂亮语法”。

这里使用继承的问题是因为红黑树算法需要BRT_node s,而不是BST_node s。因此,在这种情况下的继承是不合适的。