1. Every node is either red or black.
2. The root is black. (This rule is sometimes omitted. Since the root can always be changed from red to black.)
3. There are no 2 adjacent red nodes.
4. Every path from a given node to any of its descendant NIL nodes contains the same number of black nodes.
Lemma
A red-black tree with n internal nodes has the height at most 2log(n+1)
Proof of the balance
A simple example to understand balancing is, a chain of 3 nodes is not possible in Red Black Tree
A chain of 3 nodes is nodes is not possible in Red-Black Trees. Following are NOT Red-Black Trees 30 30 30 / / / 20 NIL 20 NIL 20 NIL / / / 10 NIL 10 NIL 10 NIL
Operation
insert / delete / lookup / print —— in O(log N) worst-case time
ps : Rotate - O(1)
left_rotate & right_rotate
1. insert - O(log N)
[step1] use the BST insert algorithm to add K to the tree — O(log N)
[step2] color the node containing K red
[step3] restore red-black tree properties (if necessary) — worst case, O(log N)
case 1 > K’s parent P is black, OK !
case 2 > K’s parent P is red, there will be 4+4 cases
first 4 cases, P’s sibling is NIL or black — change G to red!
<1> G.left = P, P.left = K — left rotate
<2> G.left = P, P.right = K — change color and K to root
<3> G.right = P, P.left = K — change color and K to root
<4> G.right = P, P.right = K
second 4 cases, P’s sibling is red — recolor all the way up