红黑树(Red-Black Tree)
void RedBlackTree::remove(int val) {
RBTreeNode* z =删除操作的完整实现涉及到查找要删除的节点,替换该节点(如果需要),以及通过`fixDelete`函数调整树以恢复红黑树的性质。
```cpp
void RedBlackTree::remove(int val) {
RBTreeNode* z = find(val); // 假设find函数已经实现,用于查找值为val的节点
if (z == nullptr) return; // 如果未找到节点,则直接返回
RBTreeNode* y = z;
RBTreeNode* x;
Color yOriginalColor = y->color;
// 如果z有一个孩子,y指向它的孩子;否则,y指向z
if (z->left == nullptr)
x = z->right;
else if (z->right == nullptr)
x = z->left;
else {
y = minimum(z->right); // 找到z的右子树中的最小节点
yOriginalColor = y->color;
x = y->right;
if (y->parent != z) {
// 如果y不是z的直接孩子,需要进行一些指针的调整
if (y->parent->left == y)
y->parent->left = y->right;
else
y->parent->right = y->right;
y->right = z->right;
y->right->parent = y;
}
// y现在是z的右子树中的最小节点,它替代了z
if (z == root)
root = y;
else if (z->parent->left == z)
z->parent->left = y;
else
z->parent->right = y;
y->parent = z->parent;
// 将y的内容复制到z中(假设节点包含除了值以外的其他数据)
// 这里我们简化处理,只复制值
z->val = y->val;
}
// 删除节点y(此时y指向z或z的替代者)
delete y;
// 如果y是黑色的,并且它不是根节点,我们需要进行调整
if (yOriginalColor == BLACK)
fixDelete(x);
}
void RedBlackTree::fixDelete(RBTreeNode* &x) {
while (x != root && (x == nullptr || x->color == BLACK)) {
if (x == x->parent->left) {
RBTreeNode* w = x->parent->right;
if (w->color == RED) {
w->color = BLACK;
x->parent->color = RED;
leftRotate(x->parent);
w = x->parent->right;
}
if (w->left->color == BLACK && w->right->color == BLACK) {
w->color = RED;
x = x->parent;
} else {
if (w->right->color == BLACK) {
w->left->color = BLACK;
w->color = RED;
rightRotate(w);
w = x->parent->right;
}
w->color = x->parent->color;
x->parent->color = BLACK;
w->right->color = BLACK;
leftRotate(x->parent);
x = root;
}
} else {
// 与上面类似,但是方向相反
}
}
if (x != nullptr)
x->color = BLACK;
}
// 假设的find函数,用于查找值为val的节点
RBTreeNode* RedBlackTree::find(int val) {
RBTreeNode* current = root;
while (current != nullptr) {
if (val < current->val)
current = current->left;
else if (val > current->val)
current = current->right;
else
return current;
}
return nullptr;
}
// 其他函数如leftRotate, rightRotate, minimum, successor等可以根据需要实现