【发布时间】:2016-09-26 08:12:05
【问题描述】:
我一整天都在盯着它看,稍微有点地方,但它仍然无法正常工作!只是试图将元素 k '放入'(真正插入或查找它是否存在)到 LL 红黑树中。这是我的方法:
Node * RPut(Node* p, const K& k, Node*& location)
{
// if you are at the bottom of the tree,
// add new node at bottom of the tree
if (p == 0)
{
// new red note with new data
location = NewNode(k, Data(), RED);
return location;
}
if(greater_(k,p->key_))
{
// if it's greater than the root, move down to the left child
p->left_ = Rput(p->left_, k, location);
}
// right subtree
else if (greater_(p->key_,k))
{
// but if the key is less than root, move down to right child
p->right_ = Rput(p->right_, k, location);
}
// if they are equal
else
{
location = p;
}
// code for rotating
// this sort of worked.
if(p->right_ && p->right_->IsRed())
{
p = RotateLeft(p);
if (p->left_->IsBlack())
{
p->SetBlack();
p->left_->SetRed();
}
}
if (p->left_ && p->left_->IsRed())
{ if (p->left_->left_ && p->left_->left_->IsRed())
{
p = RotateRight(p);
p->left_->SetBlack();
p->right_->SetBlack();
}
}
return p;
}
我知道我的旋转方法非常有效。这会正确插入到第五个元素(我没有尝试过每种组合,但通常情况下。)例如,正确插入的 abcde 将是
d
b e
a c --
[以b为红色节点]
我的工作,但停在这里,给我:
b
a d
- - c e
没有红色节点。
任何人看到我忽略的任何明显内容或为什么它无法正常工作?任何帮助都非常感谢。 谢谢!
【问题讨论】:
标签: c++ data-structures binary-search-tree red-black-tree