70 likes | 173 Views
CS 330: Algorithms 2-3-4 and Red- Black Trees. Gene Itkis. 2-3-4 trees. x y z. x y. x. > z. > z. < x. > y < z. < x. > y < z. > x < y. < x. > x < y. > x. > y. < x. > x. > x < y. > y. > x < y. < x. < x. y. y. x. x. x. z. x. y. 2-3-4 nodes:
E N D
CS 330: Algorithms2-3-4andRed-BlackTrees Gene Itkis
2-3-4 trees x y z x y x >z >z <x >y<z <x >y<z >x<y <x >x<y >x >y <x >x >x<y >y >x<y <x <x y y x x x z x y • 2-3-4 nodes: • Red-black implementation: or Gene Itkis
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 • Black node = “root” of a 2-3-4 node • Black depth = depth in 2-3-4 tree Gene Itkis
2-3-4 & Red-Black trees • 2-3-4 trees • Perfectly balanced • height ≤ lg n • Red-Black trees • 2-3-4 node = • =Red-Blacksubtree of height ≤ 2 • Red-Black tree height ≤ 2 lg n • Search (both 2-3-4 & Red-Black): O(lg n) Gene Itkis
2-3-4 tree example 2 5 2 5 7 5 5 2 6 7 8 2 7 8 5 7 8 9 6 2 6 9 8 5 2 7 5 2 7 5 5 7 2 6 8 Gene Itkis
Zoom-in: one node A A A A A C B B E D B C D B B D E D C C 4 3 5 +6 • Simple inserts: • Case 0 • No fixing needed • …even inside tree • More complex: • Case 1: • Split (3,4,5) • 4 will try to join higher • 6 can now join as case 0 • …same inside tree 4 5 4 6 5 5 5 6 4 4 6 +6 4 4 3 5 6 3 5 4 6 5 3 6 Gene Itkis
Zoom-in: one node 4 4 5 6 5 4 +6 5 4 5 4 6 5 5 • Case 0: • Case 3: • Rotate 4-5… • To get case 0 above • Case 2: • Rotate 6-5 • To get case 3 above 4 6 6 4 +6 4 4 5 5 6 5 6 4 6 6 +5 4 4 6 5 6 5 6 4 5 Gene Itkis