(1) Overview
Binary tree is a very extensive data structure, but if it is a regular insertion, it will result in a height of two fork trees and an imbalance of the whole tree. Red and black trees are a kind of balanced binary tree, the Set,map in C++stl and the data structure inside the expansion container are all red and black trees.
(2) left rotation
For example, you need to rotate X to the left node of Y. The whole algorithm is very clear: from top to bottom, get the Y pointer, say x's right pointer to the left node of Y, and then use the parent function to get the Father node of x, if null, Y is the new root, if not NULL, if X is the father's left child or right child, the pointer is pointing to Y. Finally, the left pointer of y points to X to complete the rotation. It is important to note that the algorithm is a logical step with sequential, not able to reverse the order, if the order of the change of assignment will cause memory loss pointer pointing, there is a memory error.
Code: NOTE: Parent is a function for Father node, root is a pointer that always points to the memory area of the root node.
Left rotation, assuming x->pright!=null
void Left_rotate (NODE *head,node *x)//head is the root node, X is the node to be left rotated
{
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, then place Y as root node
root=y;
else if (px->pleft==x)
px->pleft=y;
else
px->pright=y;
y->pleft=x;
}
else
printf ("The node with item%ld cannot be left-rotated.") ", X->item);
}
(3) Right rotation
The method is basically the same as the left rotation, except in the opposite direction, no longer repeating its process.
Code:
Right rotation, assuming y->pleft!=null
void Right_rotate (NODE *head,node *y)//head is the root node, Y is the node to be rotated to 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 ("The node with item%ld cannot be rotated right.") ", Y->item);
}
Return to Father 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)//found after not searching for other
return result;
if (head->pright!=null)
{
result=parent (pnode,head->pright);
if (result!=null)
return result;
}
}
Return result;//not found, returns null
}
Summary: The algorithm of rotation is very clear, the whole logical thinking is the focus.