【发布时间】:2015-04-26 06:32:32
【问题描述】:
下面是我编写的用于将节点插入到简单二叉搜索树中的代码。现在我正在尝试通过将相同的 Node 类继承到 RBNode 类来实现红黑树。
void Node::insert_node(Tree *t)
{
Node *cur_node = t->get_root();
Node *prev_node;
while(NULL != cur_node)
{
prev_node = cur_node;
if(this->data < cur_node->data)
{
cur_node = cur_node->left;
}
else
{
cur_node = cur_node->right;
}
}
if(NULL == t->get_root())
{
cur_node = this;
t->set_root(cur_node);
}
else
{
if(this->data < prev_node->data)
{
prev_node->left = this;
}
else
{
prev_node->right = this;
}
this->parent = prev_node;
}
}
对于 RBNode,此函数将保持不变,除了 Node* 应替换为 RBNode* 并且 Tree* 应替换为 RBTree*。我认为在 RBNode 类中编写相同的函数是徒劳的,它本质上做的是完全相同的事情。如果我使用相同的功能,我无法访问 RBNode 的成员,因为我插入到树中的是节点。
实现这一目标的有效方法是什么。我是 C++ 新手,所以如果我遗漏了任何明显的内容,请告诉我。
【问题讨论】:
-
如果您的目标是获得最高效率,那么像这样的数据结构会涉及大量松散的指针追逐,这可能会导致大量缓存未命中。像 B+ 树这样更连续的数据结构可能会更快。此外,根据您的实际典型数据,您甚至可能不需要树。
标签: c++ inheritance