Computer Science Dictionaries: Red-Black CS 330: Algorithms Dictionaries: and Red-Black Trees Gene Itkis
Computer Science CS-330: Algorithms, Fall 2004Gene Itkis2 Dictionary: Implementations Simple/naïve Lists Lists Better implementations Hash Tables Hash Tables Probabilistic methods, Expected values Ordered trees “Good enough” approximations; Augmenting ( order stats ) Other Skip-lists
Computer Science CS-330: Algorithms, Fall 2004Gene Itkis3 Hashing: Collision Resolution Methods Comparison Chaining Requires extra space As with linked list Stretchable Can degenerate to linked-list search Open Addressing No extra space used Has size limit Also can degenerate to unordered list search Perfect Hashing: Must know the set ahead of time (no/little dynamics) O(n) space overhead
Computer Science CS-330: Algorithms, Fall 2004Gene Itkis4 Dictionary Interface isEmpty() size() find(key) insert() insert(elem) remove() remove(key) Dynamic
Computer Science CS-330: Algorithms, Fall 2004Gene Itkis5 Ordered Trees Order x< y, z : min at root – heap ( ) y < x < z y < x < z : search Depth Shallow Balanced There might be exceptions: e.g., Leftist heaps “Strong” balance Approximate E.g., depth of leaves within factor of 2 (R-B trees) heap x z y
Computer Science CS-330: Algorithms, Fall 2004Gene Itkis6 Ordered Trees Searching Easy Insert/Delete Naïve: destroys balance Fix balance How? AVL trees Nodes keep children heights Rotate when needed: when children heights are >1 apart Red-Black2-3-4 Red-Black / trees “Almost balanced”
Computer Science CS-330: Algorithms, Fall 2004Gene Itkis trees Nodes: Redblack Red-black implementation: x y z >y<z>y<z >z>z >x<y>x<y <x<x >y>y >x<y>x<y <x<x x y >x>x<x<x x >x>x<x<x x >y>y >x<y>x<y <x<x x y y x or >y<z>y<z >z>z >x<y>x<y <x<x y z x
Computer Science CS-330: Algorithms, Fall 2004Gene Itkis8 Red-Black trees Properties: Every node is either red or black Root: black Leaf (nil): black Children of red node are black Any root-leaf path has same # of black nodes Black depth of node v = “# of black nodes on the path from root to v same for all leaves Black2-3-4 Black node = “root” of a node Black2-3-4 Black depth = depth in tree
Computer Science CS-330: Algorithms, Fall 2004Gene Itkis tree example
Computer Science CS-330: Algorithms, Fall 2004Gene Itkis tree Alwaysperfectly balanced Always remains perfectly balanced Your assignment: Red-Black Sketch your own Red-Black tree insertion pseudo-code Red-Black Read Red-Black tree insertion pseudo-code in the book Compare trees are a special case of B-trees Used in databases and disk memory management