我有一个执行重新着色和旋转的树木修复算法,当要删除的节点有2个或1个子节点时,我已经测试了这个。但是一旦他们没有孩子,我就不知道该怎么办。
由于我要传递要移除的节点的子节点,父节点以及这些子节点是左子节点还是右子节点,如果左右子节点都是NULL(与无子节点相同),则无法正常工作< / p>
我完全理解插入红黑树,但删除时我无法掌握一般的想法。提供的代码来自我的教授,但实际上我想编写自己的版本,但我不像删除那样理解删除
void RedBlackTree::rbDeleteFixUp (Node* child, Node* parent, bool isRightChild){
while (child != root && child->isBlack == true){
//Left child
if (isRightChild = false){
//Sibling
Node* sibling = parent->right;
if (sibling->isBlack = false){
sibling->isBlack = true;
child->parent->isBlack = false;
child = child->parent;
leftRotate(child);
sibling = child->parent->right;
}
if (sibling->left->isBlack == true && sibling->right->isBlack == true){
sibling->isBlack = false;
child = child->parent;
}
else{
if (sibling->right->isBlack == true){
sibling->left->isBlack = true;
sibling->isBlack = false;
rightRotate(sibling);
sibling = child->parent->right;
sibling->isBlack = child->parent->isBlack;
child->parent->isBlack = true;
sibling->right->isBlack = true;
child = child->parent;
leftRotate(child);
child = root;
}
}
}
else{
Node* sibling = parent->left;
if (sibling->isBlack = false){
sibling->isBlack = true;
child->parent->isBlack = false;
child = child->parent;
rightRotate(child);
sibling = child->parent->left;
}
if (sibling->right->isBlack == true && sibling->left->isBlack == true){
sibling->isBlack = false;
child = child->parent;
}
else{
if (sibling->left->isBlack == true){
sibling->right->isBlack = true;
sibling->isBlack = false;
leftRotate(sibling);
sibling = child->parent->right;
sibling->isBlack = child->parent->isBlack;
child->parent->isBlack = true;
sibling->left->isBlack = true;
child = child->parent;
rightRotate(child);
child = root;
}
}
}
}
}