我终于想出了如何成功地将项目插入到我的红黑树中而没有出现任何分段错误,但是,我的节点着色已关闭。
我尝试按以下顺序将以下值插入树中:4 3 2 6 5 1
当我打印出树InOrder时,我得到以下内容:1-R 2-B 3-B
4-R 5-R 6-B
当我应该得到:1-R 2-B 3-B 4-R 5-B 6-R
这是我的InsertFixUp
功能:
void RBTree::RBInsertFixUp(RBNode* z){
RBNode* y;
if(z == RBTree::root){
root->color = 'B';
}else{
while(z->parent->color == 'R'){
if(z->parent == z->parent->parent->left){
y = z->parent->parent->right;
if(y->color == 'R'){
z->parent->color = 'B'; //Case 1 Check
y->color = 'B'; //Case 1 Check
z->parent->parent->color = 'R'; //Case 1 Check
z = z->parent->parent; //Case 1
}else{
if(z == z->parent->right){
z = z->parent; //Case 2
RBLeftRotate(z); //Case 2 Look at Rotate
}
z->parent->color = 'B'; //Case 3 Check
z->parent->parent->color = 'R'; //Case 3 Check
RBRightRotate(z->parent->parent); //Case 3 Look at Rotate
}
}else{
y = z->parent->parent->left;
if(y->color = 'R'){
z->parent->color = 'B'; //Case 1 Check
y->color = 'B'; //Case 1 Check
z->parent->parent->color = 'R'; //Case 1 Check
z = z->parent->parent; //Case 1
}else{
if(z = z->parent->left){
z = z->parent; //Case 2
RBRightRotate(z); //Case 2 Look at Rotate
}
z->parent->color = 'B'; //Case 3 Check
z->parent->parent->color = 'R'; //Case 3 Check
RBLeftRotate(z->parent->parent); //Case 3 Look at Rotate
}
}
}
root->color = 'B';
}
这是我的左右旋转:
void RBTree::RBLeftRotate(RBNode* x){
RBNode* y = x->right;
x->right = y->left;
y->left->parent = x;
y->parent = x->parent;
if(x->parent == RBTree::Tnil){
root = y;
}else if(x == x->parent->left){
x->parent->left = y;
}else{
x->parent->right = y;
}
y->left = x;
x->parent = y;
}
void RBTree::RBRightRotate(RBNode* x){
RBNode* y = x->left;
x->left = y->right;
y->right->parent = x;
y->parent = x->parent;
if(x->parent == RBTree::Tnil){
root = y;
}else if(x == x->parent->right){
x->parent->right = y;
}else{
x->parent->left = y;
}
y->right = x;
x->parent = y;
}
从我能看到的一切,我的色彩是正确的,我的旋转也是,但也许我错过了一些东西。关于为什么我的着色会关闭的任何帮助都会很棒。
答案 0 :(得分:0)
在非红色叔叔路径的第二次轮换中(她从z->父级是左子分支):
RBRightRotate(z->parent->parent); //Case 3 Look at Rotate
您正在祖父母节点上旋转,但如果z和z->父级具有不同的方向,则z已经向上移动了一个级别。
我建议将整个非红叔叔路径设为以下(父亲是右子路径留给你):
if(z == z->parent->right)
RBLeftRotate(z->parent);
else
z = z->parent;
z->color = 'B';
z->parent->color = 'R';
RBRightRotate(z->parent);