Red Black Trees
So… Btrees self balance Can represent as a binary tree…
Red Black Tree Red Black Tree = binary version of BTree Red nodes are part of their parent 1 red + 1 black = node degree 3 2 red + black = node degree 4
Red Black vs BTree Two views of same tree Btree degree 4: Red Black Tree
Red Black Rules Rules The root is black
Red Black Rules Rules The root is black – if it becomes red, turn it back to black Null values are black A red node must have black children Every path from root to leaf must have same number of black nodes
Guarantee Worst and best case in terms of red nodes for black height = 2 If L = num leaves, B = black height 2B ≤ L ≤ 22B
Guarantee So… 2 𝐵 ≤ 𝐿 ≤ 2 2𝐵 𝐵 ≤ 𝑙𝑜𝑔 2 𝐿 ≤2𝐵 1 𝐵 ≥ 1 𝑙𝑜𝑔 2 𝐿 ≥ 1 2𝐵 𝑙𝑜𝑔 2 𝐿 𝐵 ≥ 1 ≥ 𝑙𝑜𝑔 2 𝐿 2𝐵 𝑙𝑜𝑔 2 𝐿 ≥ 𝐵 ≥ 𝑙𝑜𝑔 2 𝐿 2
Height 𝑙𝑜𝑔 2 𝐿 ≥ 𝐵 Black height is O(logL) Total height at most 2B 2O(logL) = O(logL) Height is O(logL) Total nodes (N) < 2L – 1 O(log(n/2)) = O(logn) Guaranteed logN performance 𝑙𝑜𝑔 2 𝐿 ≥ 𝐵
Actual Work Insert as normal New node is always red Two red's in a row need to be fixed…
Fixes Red child, red parent, no uncle or black uncle Zig-zag style double rotation New parent becomes black, new child red == Rearranging values in 4 node of BTree
Fixes Red child has red parent and red uncle Push up redness of siblings to grandparent Fix at grandparent if new problem If root becomes red, make it black == Splitting a node with 4 keys in BTree
RB Deletions Need to preserve no red->red Need to preserve consistent black height Tools : Recolors and rotates
RB Deletions Lots of special cases… some easy, some tricky
Binary Tree Comparisons Plain BST Maintains data in sorted order Hopefully O(logn) Could be O(n)
Binary Tree Comparisons Splay Pull nodes to Amortized O(logn) Ideal for consecutive accesses
Binary Tree Comparisons AVL Guaranteed O(logn) Height limited to ~1.44 log2(n) High constant factors on insert/delete
Binary Tree Comparisons Red/Black Guaranteed O(logn) Height limited to ~2 log2(n) Less balanced than AVL Faster insert/remove Slower find Standard implementation for most library BSTs
Tree Comparisons BTree Not binary – can pick any node size Still sorted Self balancing – log(n) performance Ideal for slower storage Model for red/black trees
Tree Comparisons Other trees Represent tree structure Not necessarily sorted