C++ 红黑树算法的旋转问题
首先,很抱歉我的英语不好 我试图实现红黑树算法,但我有红黑树算法的问题,特别是“旋转权” 我遵循了这张图片 这是我的密码C++ 红黑树算法的旋转问题,c++,red-black-tree,C++,Red Black Tree,首先,很抱歉我的英语不好 我试图实现红黑树算法,但我有红黑树算法的问题,特别是“旋转权” 我遵循了这张图片 这是我的密码 void RedBlackTree::right_rotate(Node*& root, Node*& y) { Node* x = y->left; y->left = x->right; if (y->left != NULL) y->left->parent = y;
void RedBlackTree::right_rotate(Node*& root, Node*& y)
{
Node* x = y->left;
y->left = x->right;
if (y->left != NULL)
y->left->parent = y;
x->parent = y->parent;
// ERROR!!!!
if (y->parent == NULL)
root = x;
else if (y == y->parent->left)
y->parent->left = x;
else
y->parent->right = x;
x->right = y;
y->parent = x;
}
正如您在注释中所看到的,在更改“x”节点的父节点后,我与“y”节点存在访问冲突。
我可以检查y值是否变为null,只要该行被执行
我该怎么办??
谢谢
***这是我代码的一部分
struct Node
{
int data;
bool redflag; // true면 red , false면 black
Node* left, * right, * parent;
Node(int data)
{
this->data = data;
left = right = parent = NULL;
this->redflag = true;
}
};
//
class RedBlackTree
{
private:
Node* root;
protected:
void left_rotate(Node*& root, Node*& node);
void right_rotate(Node*& root, Node*& node);
void insert_fixup(Node*& root, Node*& node);
public:
RedBlackTree() { root = NULL; }
~RedBlackTree() { root = NULL; }
void insert_node(const int& n);
void inorder();
};
Node* BSTInsert(Node* root, Node* node)
{
if (root == NULL)
return node;
if (node->data < root->data)
{
root->left = BSTInsert(root->left, node);
root->left->parent = root;
}
else if (node->data > root->data)
{
root->right = BSTInsert(root->right, node);
root->right->parent = root;
}
return root;
}
void RedBlackTree::insert_node(const int& _data)
{
Node* node = new Node(_data);
root = BSTInsert(root, node);
insert_fixup(root, node);
inorder();
}
struct节点
{
int数据;
bool redflag;//true면 红色,假的면 黑色
节点*左、*右、*父节点;
节点(int数据)
{
这->数据=数据;
左=右=父=空;
此->redflag=true;
}
};
//
类红黑树
{
私人:
节点*根;
受保护的:
无效左旋转(节点*&根,节点*&节点);
无效右旋转(节点*&根,节点*&节点);
void insert_fixup(节点*&根,节点*&节点);
公众:
RedBlackTree(){root=NULL;}
~RedBlackTree(){root=NULL;}
无效插入节点(常量int&n);
无效顺序();
};
节点*BSTInsert(节点*根,节点*节点)
{
if(root==NULL)
返回节点;
如果(节点->数据<根->数据)
{
根->左=插入(根->左,节点);
根->左->父=根;
}
else if(节点->数据>根->数据)
{
根->右=插入(根->右,节点);
根->右->父=根;
}
返回根;
}
void RedBlackTree::插入节点(常量int&\u数据)
{
节点*节点=新节点(_数据);
根=插入(根,节点);
插入\u fixup(根、节点);
顺序();
}
在取消引用之前,应检查所有指针的numptr
。