[Java] 纯文本查看 复制代码
boolean Insert(const K& key, const V& value)
{
//根节点为空
if (_root == NULL)
{
_root = new Node(key,value);
_root->_color = BLACK;
return true;
}
//根节点不为空
//找到新节点插入位置
Node* parent = NULL;
Node* cur = _root;
while (cur)
{
if (cur->_key < key)
{
parent = cur;
cur = cur->_right;
}
else if (cur->_key >key)
{
parent = cur;
cur = cur->_left;
}
else
return false;
}
//插入新节点
cur = new Node(key, value);
cur->_color = RED;
if (parent->_key > key)
{
parent->_left = cur;
cur->_parent = parent;
}
else//parent->_key < key
{
parent->_right = cur;
cur->_parent = parent;
}
//插入节点后颜色的调整
while (parent && parent->_color == RED)
{
Node* grandfather = parent->_parent;//grandfather颜色一定为黑色
if (parent == grandfather->_left)
{
Node* uncle = grandfather->_right;
//uncle存在且为红
if (uncle && uncle->_color == RED)
{
parent->_color = uncle->_color = BLACK;
grandfather->_color = RED;
cur = grandfather;
parent = cur->_parent;
}
else//uncle不存在/uncle存在且为黑
{
if (cur == parent->_right)
{
RotateL(parent);
swap(parent, cur);
}
RotateR(grandfather);
parent->_color = BLACK;
grandfather->_color = RED;
}
}
else//grandfather->_right==parent
{
Node* uncle = grandfather->_left;
//uncle存在且为红
if (uncle && uncle->_color == RED)
{
parent->_color = uncle->_color = BLACK;
grandfather->_color = RED;
cur = grandfather;
parent = cur->_parent;
}
else//不存在/存在且为黑
{
if (cur == parent->_left)
{
RotateR(parent);
swap(cur, parent);
}
RotateL(grandfather);
parent->_color = BLACK;
grandfather->_color = RED;
}
}
}//end while (parent && parent->_color == RED)
_root->_color = BLACK;
return true;
}