Red-black tree algorithm to resolve the internal structure

 

 

 / ** the From the CLR * / 
    Private  void fixAfterInsertion (the Entry <K, V> X) { 
        x.color = RED;
 
the while (! X = null && && x.parent.color the root X = ==! RED) {
// currently inserted is the parent node of the current node's left child node into the ancestor node
IF (parentOf (X) == leftOf (parentOf (parentOf (X)))) {
// get the current node's right child node ancestor of the entry
<K , V> Y = RightOf (parentOf (parentOf (X)));

// colorOf (Y) method if y == null null is returned black
IF (colorOf (Y) == RED) { the setColor (parentOf (X), BLACK); the setColor (Y, BLACK); the setColor (parentOf (parentOf (X)), RED); X = parentOf (parentOf (X)); } the else {
// RightOf (parentOf (X)) to give the right child node of the current node's parent node
IF (X == RightOf (parentOf (X))) { X = parentOf (X); RotateLeft (X); }
// set parent node to black the setColor (parentOf (X), bLACK);
// set ancestor node red setColor (parentOf (parentOf (X)), RED);
// for right-handed operation, passing an ancestor node RotateRight (parentOf (parentOf (X))); } }

the else { Entry<K,V> y = leftOf(parentOf(parentOf(x))); if (colorOf(y) == RED) { setColor(parentOf(x), BLACK); setColor(y, BLACK); setColor(parentOf(parentOf(x)), RED); x = parentOf(parentOf(x)); } else { if (x == leftOf(parentOf(x))) { x = parentOf(x); rotateRight(x); } setColor(parentOf(x), BLACK); the setColor (parentOf (parentOf (X)), RED); RotateLeft (parentOf (parentOf (X))); } } }
// root to black root.color
= BLACK; }
// D- 

// When do I need a right-handed:
// 1: insert the current node's parent node is a left child node ancestor node
// 2: Right uncle of the current node is inserted node is nil or black

// or
1: The current node's parent node is inserted into the right child node of ancestor

/** From CLR */ private void rotateRight(Entry<K,V> p) { if (p != null) { Entry<K,V> l = p.left; p.left = l.right; if (l.right != null) l.right.parent = p; l.parent = p.parent; if (p.parent == null) root = l; else if (p.parent.right == p) p.parent.right = l; else p.parent.left = l; l.right = p; p.parent = l; } }

  

//左旋  
/** From CLR */ private void rotateLeft(Entry<K,V> p) { if (p != null) { Entry<K,V> r = p.right; p.right = r.left; if (r.left != null) r.left.parent = p; r.parent = p.parent; if (p.parent == null) root = r; else if (p.parent.left == p) p.parent.left = r; else p.parent.right = r; r.left = p; p.parent = r; } }

  

Guess you like

Origin www.cnblogs.com/softxiaohui/p/11072119.html