void rb_insertFixup(rbt *t, rbnode *n) { rbnode *y = NULL; while (n->parent != NULL && n->parent->color == RED) { if (n->parent == getGrandParent(n)->link[0]) { y = getUncle(n); if (y != NULL && y->color == RED) { n->parent->color = BLACK; y->color = BLACK; n = getGrandParent(n); if(n != NULL) n->color = RED; } else { if (n == n->parent->link[1]) { n = n->parent; leftRotate(t, n); } n->parent->color = BLACK; getGrandParent(n)->color = RED; rightRotate(t, getGrandParent(n)); } } else { y = getUncle(n); if (y != NULL && y->color == RED) { n->parent->color = BLACK; y->color = BLACK; n = getGrandParent(n); if(n != NULL) n->color = RED; } else { if (n == n->parent->link[0]) { n = n->parent; rightRotate(t, n); } n->parent->color = BLACK; getGrandParent(n)->color = RED; leftRotate(t, n->parent->parent); } } } // save us from a red violation at the root (t->root)->color = BLACK; }
void RedBlackTree::insertFixup(TreeNode * pNode) { if (pNode == m_pSentinel) { return; // impossible actually. } TreeNode * pUncle = m_pSentinel; TreeNode * pGrandParent = NULL; while (pNode != m_pRoot && red == pNode->parent->color) { pUncle = getUncle(pNode); pGrandParent = getGrandParent(pNode); if (pUncle != NULL && pUncle != m_pSentinel && pUncle->color == red) { pNode->parent->color = black; pUncle->color = black; pGrandParent->color = red; pNode = pGrandParent; } else { if (pNode->parent == pGrandParent->left) { if (pNode == pNode->parent->right) { pNode = pNode->parent; rotateLeft(pNode); } pNode->parent->color = black; pGrandParent->color = red; rotateRight(pGrandParent); } else { if (pNode == pNode->parent->left) { pNode = pNode->parent; rotateRight(pNode); } pNode->parent->color = black; pGrandParent->color = red; rotateLeft(pGrandParent); } } } m_pRoot->color = black; }
TreeNode * RedBlackTree::getUncle(const TreeNode * pNode) { TreeNode * p = getGrandParent(pNode) ; if (p == m_pSentinel) { return m_pSentinel ; } if (p->left == pNode->parent) { return p->right ; } else { return p->left ; } return m_pSentinel ; }
void RedBlackTree::CheckInsert(RBNode* node) { if(node->parent == m_nil) { node->bRed = false; return; } if(!node->parent->bRed) { return; } if(getUncle(node)->bRed) { node->parent->bRed = false; getUncle(node)->bRed = false; getGrandParent(node)->bRed = true; CheckInsert(getGrandParent(node)); return; } if(node == node->parent->right && node->parent == getGrandParent(node)->left) { RotateLeft(node->parent); node = node->left; } else if(node == node->parent->left && node->parent == getGrandParent(node)->right) { RotateRight(node->parent); node = node->right; } node->parent->bRed = false; getGrandParent(node)->bRed = true; if(node == node->parent->left) { RotateRight(getGrandParent(node)); } else { RotateLeft(getGrandParent(node)); } }