Presentation is loading. Please wait.

Presentation is loading. Please wait.

Red Black Trees.

Similar presentations


Presentation on theme: "Red Black Trees."— Presentation transcript:

1 Red Black Trees

2 So… Btrees self balance Can represent as a binary tree…

3 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

4 Red Black vs BTree Two views of same tree
Btree degree 4: Red Black Tree

5 Red Black Rules Rules The root is black

6 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

7 Guarantee Worst and best case in terms of red nodes for black height = 2 If L = num leaves, B = black height B ≤ L ≤ 22B

8 Guarantee So… 2 𝐵 ≤ 𝐿 ≤ 2 2𝐵 𝐵 ≤ 𝑙𝑜𝑔 2 𝐿 ≤2𝐵
1 𝐵 ≥ 1 𝑙𝑜𝑔 2 𝐿 ≥ 1 2𝐵 𝑙𝑜𝑔 2 𝐿 𝐵 ≥ ≥ 𝑙𝑜𝑔 2 𝐿 2𝐵 𝑙𝑜𝑔 2 𝐿 ≥ 𝐵 ≥ 𝑙𝑜𝑔 2 𝐿 2

9 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 𝐿 ≥ 𝐵

10 Actual Work Insert as normal New node is always red
Two red's in a row need to be fixed…

11 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

12 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

13 RB Deletions Need to preserve no red->red
Need to preserve consistent black height Tools : Recolors and rotates

14 RB Deletions Lots of special cases… some easy, some tricky

15 Binary Tree Comparisons
Plain BST Maintains data in sorted order Hopefully O(logn) Could be O(n)

16 Binary Tree Comparisons
Splay Pull nodes to Amortized O(logn) Ideal for consecutive accesses

17 Binary Tree Comparisons
AVL Guaranteed O(logn) Height limited to ~1.44 log2(n) High constant factors on insert/delete

18 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

19 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

20 Tree Comparisons Other trees Represent tree structure
Not necessarily sorted


Download ppt "Red Black Trees."

Similar presentations


Ads by Google