(1) Overview
A binary tree is a widely used data structure. However, regular insertion may result in an excessively high height and an imbalance of the entire tree. The red-black tree is a balanced binary tree. The set, map, and the internal data structures of the C ++ STL containers are all red-black trees.
(2) left Rotation
For example, you need to rotate x to the left node of y. The idea of the entire algorithm is very clear: from top to bottom, get the y pointer first, talk about the right pointer of x pointing to the left node of y, and then use the parent function to get the father node of x, if it is NULL, y is the new root. If it is not NULL, x points the pointer to y based on whether x is the father's left or right child. Finally, point the left pointer of y to x to complete the rotation. It is worth noting that the algorithm is an ordered logical step and cannot be changed. changing the order of values may cause memory pointer loss and memory errors.
Code: Note: parent is a function used to find the parent node. root is a pointer that always points to the memory area of the root node.
[Cpp]
// Rotate left. Suppose x-> pRight! = NULL
Void left_rotate (NODE * head, NODE * x) // head is the root NODE, and x is the NODE to be rotated on the left.
{
If (x-> pRight! = NULL)
{
NODE * y = x-> pRight;
If (y-> pLeft! = NULL)
X-> pRight = y-> pLeft;
NODE * px = parent (x, head );
If (px = NULL) // if x is the root node, set y to the root node.
Root = y;
Else if (px-> pLeft = x)
Px-> pLeft = y;
Else
Px-> pRight = y;
Y-> pLeft = x;
}
Else
Printf ("node with item % ld cannot be left rotated! ", X-> item );
}
(3) Right Rotation
The method is basically the same as the left rotation method, but the opposite direction is used.
Code:
[Cpp]
// Right rotation. Suppose y-> pLeft! = NULL
Void right_rotate (NODE * head, NODE * y) // head is the root NODE, and y is the NODE to be rotated on the right.
{
If (y-> pLeft! = NULL)
{
NODE * x = y-> pLeft;
If (x-> pRight! = NULL)
Y-> pLeft = x-> pRight;
NODE * py = parent (y, head );
If (py = NULL)
Root = x;
Else if (py-> pLeft = y)
Py-> pLeft = x;
Else
Py-> pRight = x;
X-> pRight = y;
}
Else
Printf ("node with item % ld cannot be right rotated! ", Y-> item );
}
[Cpp]
// Return the parent node
NODE * parent (NODE * pNode, NODE * head)
{
NODE * result = NULL;
If (head! = NULL)
{
If (head-> pLeft = pNode | head-> pRight = pNode)
Return head;
If (head-> pLeft! = NULL)
{
Result = parent (pNode, head-> pLeft );
If (result! = NULL) // if it is found, no other search will be performed.
Return result;
}
If (head-> pRight! = NULL)
{
Result = parent (pNode, head-> pRight );
If (result! = NULL)
Return result;
}
}
Return result; // No. NULL is returned.
}
Conclusion: The idea of rotating algorithms is very clear, and the entire logic thinking is the focus.
From byoon