#include <iostream>
#include <stack>
using namespace std;
typedef enum {
Red, Black,
} Color;
typedef struct Node {
int key;
Color color;
struct Node *p;
struct Node *left;
struct Node *right;
} Node, *ptrNode;
class RedBlackTree {
private:
ptrNode tree;
ptrNode NIL;
public:
void init();
bool empty();
void insert(int key);
void insertFixup(ptrNode cur);
void leftRotate(ptrNode p);
void rightRotate(ptrNode p);
void traverse();
};
void RedBlackTree::traverse() {
ptrNode p = tree;
stack<ptrNode> s;
while (p != NIL || !s.empty()) {
if (p != NIL) {
s.push(p);
p = p->left;
} else {
std::cout << s.top()->key << " ";
p = s.top()->right;
s.pop();
}
}
std::cout << std::endl;
}
void RedBlackTree::rightRotate(ptrNode p) {
ptrNode lchild = p->left;
p->left = lchild->right;
lchild->right->p = p;
lchild->p = p->p;
if (p->p == NIL) {
tree = lchild;
} else {
if (p == p->p->left) {
p->p->left = lchild;
} else {
p->p->right = lchild;
}
}
lchild->right = p;
p->p = lchild;
}
void RedBlackTree::leftRotate(ptrNode p) {
ptrNode rchild = p->right;
p->right = rchild->left;
rchild->left->p = p;
rchild->p = p->p;
if (p->p == NIL) {
tree = rchild;
} else {
if (p == p->p->left) {
p->p->left = rchild;
} else {
p->p->right = rchild;
}
}
rchild->left = p;
p->p = rchild;
}
void RedBlackTree::insertFixup(ptrNode cur) {
ptrNode uncle;
while (cur->p->color == Red) {
if (cur->p == cur->p->p->left) {
uncle = cur->p->p->right;
if (uncle->color == Red) {
cur->p->color = Black;
uncle->color = Black;
cur->p->p->color = Red;
cur = cur->p->p;
} else {
if (cur == cur->p->right) {
cur = cur->p;
leftRotate(cur);
}
cur->p->color = Black;
cur->p->p->color = Red;
rightRotate(cur->p->p);
}
} else {
uncle = cur->p->p->left;
if (uncle->color == Red) {
cur->p->color = Black;
uncle->color = Black;
cur->p->p->color = Red;
cur = cur->p->p;
} else {
if (cur == cur->p->left) {
cur = cur->p;
rightRotate(cur);
}
cur->p->color = Black;
cur->p->p->color = Red;
leftRotate(cur->p->p);
}
}
}
tree->color = Black;
}
void RedBlackTree::insert(int key) {
ptrNode p = new Node();
p->key = key;
p->color = Red;
p->left = NIL;
p->right = NIL;
ptrNode parent = NIL;
ptrNode cur = tree;
while (cur != NIL) {
parent = cur;
if (key < cur->key) {
cur = cur->left;
} else {
cur = cur->right;
}
}
p->p = parent;
if (parent == NIL) {
tree = p;
} else if (key < parent->key) {
parent->left = p;
} else {
parent->right = p;
}
insertFixup(p);
}
bool RedBlackTree::empty() {
if (tree == NIL) {
return true;
}
return false;
}
void RedBlackTree::init() {
NIL = new Node();
NIL->color = Black;
NIL->p = NULL;
NIL->left = NULL;
NIL->right = NULL;
tree = NIL;
}
int main() {
RedBlackTree *rbt = new RedBlackTree();
rbt->init();
rbt->insert(11);
rbt->insert(2);
rbt->insert(14);
rbt->insert(1);
rbt->insert(7);
rbt->insert(15);
rbt->insert(5);
rbt->insert(8);
rbt->insert(4);
rbt->traverse();
delete rbt;
return 0;
}
红黑树——旋转、插入操作
最新推荐文章于 2025-04-16 09:59:47 发布