1. Nature
A red-black tree is a binary lookup tree, but each node adds a field that represents the node color (red or black) and satisfies the criteria:
- Each node is either red or black.
- The root node is black.
- Each leaf node (NIL) is black.
- If a node is red, then its two sons are black.
- For each node, the same number of black nodes are included on all paths from that node to its descendants
To facilitate the processing of boundary conditions, we use a Sentinel to represent nil, if a node does not have a child node or a parent node, then the corresponding pointer of the junction points to nil.
The height of a red-black tree with n internal nodes (excluding nil) is 2LG (n+1).
2. Rotate
When you perform an INSERT or delete operation on a red-black tree, the results may violate the nature of the red-black tree, and we need to change the tree's pointer structure to preserve the nature of the red-black tree. Rotation is the correction process will be used in the operation, divided into left and right, here only to describe the left-hand operation, right-handed just opposite to the left-hand operation. The following are the rotated
left-ROTATE (T, x) y←right[x] right[x]←left[x] if left[y]! = Nil[t] P[left[y] ]←x p[y]←p[x] if p[x] = nil[t] root[t]←y Elseif x = Left[p[x]] left[p[x]]←y else right[p[x]]←y left[y]←x p[x]←y
3. Insert
The insert operation is close to the normal binary tree insert operation, setting the new insertion node to red (as little as possible against the binary tree nature), and adding Rb-insert-fixup (T, z) at the end to adjust the binary tree to satisfy the nature of the red-black tree.
rb-INSERT y←nil[t] x←root[t] whileX! =Nil[t] Doy←xifKEY[Z] <Key[x] x←left[x]ElseX←right[x] P[z]←yify =Nil[t] root[t]=ZElse ifKEY[Z] <Key[y] Left[y]←zElseright[y]←z left[z]←nil[t] right[z]←nil[t] color[z]←red RB-insert-fixup (T, z)
Red and black Trees