Red-Black Tree Neil Tang 02/04/2010 CS223 Advanced Data Structures and Algorithms
CS223 Advanced Data Structures and Algorithms Class Overview Definition Tree height Rotation and color flip Insert CS223 Advanced Data Structures and Algorithms
CS223 Advanced Data Structures and Algorithms Definition A red-black tree is a special binary search tree in which every node is either red or black; the root is black; if a node is red, then both its children are black; every simple path from a node to a null reference contains the same number of black nodes. CS223 Advanced Data Structures and Algorithms
CS223 Advanced Data Structures and Algorithms Definition CS223 Advanced Data Structures and Algorithms
CS223 Advanced Data Structures and Algorithms Height Theorem: A red-black tree with N nodes has height at most 2log(N+1). (pp.274 Cormen’s book) Experiments suggests that the average red-black tree is about as deep as an average AVL tree. The rotation happens less frequently. CS223 Advanced Data Structures and Algorithms
CS223 Advanced Data Structures and Algorithms An Example CS223 Advanced Data Structures and Algorithms
CS223 Advanced Data Structures and Algorithms Insertion Always color the new node to be inserted red. Remember that the new node will always be a leaf node right after insertion. If its parent is black, done! If its parent is red, perform a single (double) rotation! CS223 Advanced Data Structures and Algorithms
CS223 Advanced Data Structures and Algorithms Rotation if S is Black CS223 Advanced Data Structures and Algorithms
CS223 Advanced Data Structures and Algorithms Color Flip if S is red CS223 Advanced Data Structures and Algorithms
CS223 Advanced Data Structures and Algorithms Example: Insert 45 CS223 Advanced Data Structures and Algorithms
CS223 Advanced Data Structures and Algorithms Insert CS223 Advanced Data Structures and Algorithms
CS223 Advanced Data Structures and Algorithms Insert CS223 Advanced Data Structures and Algorithms
CS223 Advanced Data Structures and Algorithms Insert CS223 Advanced Data Structures and Algorithms