

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


A Red-Black tree is a binary search tree where each node is colored either RED or BLACK such that the following invariants are satisfied:
To understand invariant (3), it may be easier to conceptualize the tree such that the nodes with less than two children are linked to NIL leaves, see Figure below. Thus invariant (3) becomes: any path from the root to a NIL leaf has to have the same number of BLACK nodes.
Note that if invariant (3) holds for the root, then it must also hold for any node x in the tree (that is, the number of black nodes from an arbitrary node in a RB-tree to all “leaves” in its subtree is the same).
The RB-tree invariants guarantee that the height of a RB-tree is Θ(lg n).
Theorem: A red-black tree with n elements has height Θ(lg n).
Proof: All paths from root to a leaf must have the same number of black nodes, but we can have red nodes interleaved between black nodes. This means that the the longest and shortest path from the root to a leaf are such that hmax ≤ 2 hmin. Then using the fact that a complete binary tree of height h has 2h+1^ − 1 nodes, we get that 2 hmin+1^ − 1 ≤ n ≤ 2 hmax+1^ − 1
and from here [...] we get that hmax = Θ(lg n)
INSERT(T, k): An insertion in a Red-Black tree is the same as insertion in a binary search tree, searching for k starting from the root, until reaching NULL and inserting a node with key k as a leaf node; at the end the new node must be given a color. The question is what color: We can’t make it BLACK (bacause it violates inv. 3), so we color it RED. This may violate invariant (2) between the node and its parent. We’ll try to fix the violation by recoloring, or move the violation up the tree, until it can be fixed.
Let x be the current node (initially this is the leaf we just inserted); it is RED; it’s children, if they exist, are BLACK (initially x is a leaf so it has no children so this is true).
Note: The symmetrical case where x is a left child, and it parent is a right child is handled symmetrically: Rotate-right at x, and transform to case 3.