90 likes | 261 Views
Design and Analysis of Algorithms Red-Black trees. Haidong Xue Summer 2012, at GSU. Tree height is crucial. SEARCH(S, k) MINIMUM(S) MAXIMUM(S) SUCCESSOR(S, x) PREDECESSOR(S, x) INSERT(S, x) DELETE(S, x). O(h). O(h). O(h). O(h). O(h). O(h). O(h).
E N D
Design and Analysis of Algorithms Red-Black trees HaidongXue Summer 2012, at GSU
Tree height is crucial • SEARCH(S, k) • MINIMUM(S) • MAXIMUM(S) • SUCCESSOR(S, x) • PREDECESSOR(S, x) • INSERT(S, x) • DELETE(S, x) O(h) O(h) O(h) O(h) O(h) O(h) O(h) Red-Black tree guarantees that h<=2 lg(n+1)
What is a RBT • A binary search tree • Red-black properties: • Every node is either red or black • The root is black • Every leaf(NIL) is black • If a node is red, then both its children are black • For each node, all simple paths from the node to descendant leaves contain the same number of black nodes
What is a RBT 11 9 12 8 10 11 NIL 2 NIL NIL NIL NIL NIL NIL NIL A RBT h<=2 lg(n+1)
How to maintain a RBT • After TREE-INSERT or TREE-DELETE • It is still a binary search tree • But may not still be a RBT • After each insertion or deletion the tree need to be maintained by • RB-INSERT-FIXUP • or RB-DELETE-FIXUP
How to maintain a RBT A component used in RB-INSERT-FIXUP or RB-DELETE-FIXUP is rotation 11 Right rotate (x, y) Link y’s parent to x 9 12 Set x’s right y’s left Set y as x’s right 8 10 11 2 Rotation does not violate binary search tree properties
How to maintain a RBT 11 10 9 12 8 11 Left rotate 2