SlideShare a Scribd company logo
1 of 36
Algorithms
Red-Black Trees
Red-Black Trees
● Red-black trees:
■ Binary search trees augmented with node color
■ Operations designed to guarantee that the height
h = O(lg n)
● First: describe the properties of red-black trees
● Then: prove that these guarantee h = O(lg n)
● Finally: describe operations on red-black trees
Red-Black Properties
● The red-black properties:
1. Every node is either red or black
2. Every leaf (NULL pointer) is black
○ Note: this means every “real” node has 2 children
3. If a node is red, both children are black
○ Note: can’t have 2 consecutive reds on a path
4. Every path from node to descendent leaf contains
the same number of black nodes
5. The root is always black
Red-Black Trees
● Put example on board and verify properties:
1. Every node is either red or black
2. Every leaf (NULL pointer) is black
3. If a node is red, both children are black
4. Every path from node to descendent leaf contains
the same number of black nodes
5. The root is always black
● black-height: # black nodes on path to leaf
■ Label example with h and bh values
David Luebke 5 02/10/17
Height of Red-Black Trees
● What is the minimum black-height of a node
with height h?
● A: a height-h node has black-height ≥ h/2
● Theorem: A red-black tree with n internal
nodes has height h ≤ 2 lg(n + 1)
● How do you suppose we’ll prove this?
RB Trees: Proving Height Bound
● Prove: n-node RB tree has height h ≤ 2 lg(n+1)
● Claim: A subtree rooted at a node x contains
at least 2bh(x)
- 1 internal nodes
■ Proof by induction on height h
■ Base step: x has height 0 (i.e., NULL leaf node)
○ What is bh(x)?
RB Trees: Proving Height Bound
● Prove: n-node RB tree has height h ≤ 2 lg(n+1)
● Claim: A subtree rooted at a node x contains
at least 2bh(x)
- 1 internal nodes
■ Proof by induction on height h
■ Base step: x has height 0 (i.e., NULL leaf node)
○ What is bh(x)?
○ A: 0
○ So…subtree contains 2bh(x)
- 1
= 20
- 1
= 0 internal nodes (TRUE)
RB Trees: Proving Height Bound
● Inductive proof that subtree at node x contains
at least 2bh(x)
- 1 internal nodes
■ Inductive step: x has positive height and 2 children
○ Each child has black-height of bh(x) or bh(x)-1 (Why?)
○ The height of a child = (height of x) - 1
○ So the subtrees rooted at each child contain at least
2bh(x)-1
- 1 internal nodes
○ Thus subtree at x contains
(2bh(x)-1
- 1) + (2bh(x)-1
- 1) + 1
= 2•2bh(x)-1
- 1 = 2bh(x)
- 1 nodes
RB Trees: Proving Height Bound
● Thus at the root of the red-black tree:
n ≥ 2bh(root)
- 1 (Why?)
n ≥ 2h/2
- 1 (Why?)
lg(n+1) ≥ h/2 (Why?)
h ≤ 2 lg(n + 1) (Why?)
Thus h = O(lg n)
RB Trees: Worst-Case Time
● So we’ve proved that a red-black tree has
O(lg n) height
● Corollary: These operations take O(lg n) time:
■ Minimum(), Maximum()
■ Successor(), Predecessor()
■ Search()
● Insert() and Delete():
■ Will also take O(lg n) time
■ But will need special care since they modify tree
Red-Black Trees: An Example
● Color this tree: 7
5 9
1212
5 9
7
Red-black properties:
1. Every node is either red or black
2. Every leaf (NULL pointer) is black
3. If a node is red, both children are black
4. Every path from node to descendent leaf
contains the same number of black nodes
5. The root is always black
● Insert 8
■ Where does it go?
Red-Black Trees:
The Problem With Insertion
12
5 9
7
1. Every node is either red or black
2. Every leaf (NULL pointer) is black
3. If a node is red, both children are black
4. Every path from node to descendent leaf
contains the same number of black nodes
5. The root is always black
● Insert 8
■ Where does it go?
■ What color
should it be?
Red-Black Trees:
The Problem With Insertion
12
5 9
7
8
1. Every node is either red or black
2. Every leaf (NULL pointer) is black
3. If a node is red, both children are black
4. Every path from node to descendent leaf
contains the same number of black nodes
5. The root is always black
● Insert 8
■ Where does it go?
■ What color
should it be?
Red-Black Trees:
The Problem With Insertion
12
5 9
7
8
1. Every node is either red or black
2. Every leaf (NULL pointer) is black
3. If a node is red, both children are black
4. Every path from node to descendent leaf
contains the same number of black nodes
5. The root is always black
Red-Black Trees:
The Problem With Insertion
● Insert 11
■ Where does it go?
1. Every node is either red or black
2. Every leaf (NULL pointer) is black
3. If a node is red, both children are black
4. Every path from node to descendent leaf
contains the same number of black nodes
5. The root is always black
12
5 9
7
8
Red-Black Trees:
The Problem With Insertion
● Insert 11
■ Where does it go?
■ What color?
1. Every node is either red or black
2. Every leaf (NULL pointer) is black
3. If a node is red, both children are black
4. Every path from node to descendent leaf
contains the same number of black nodes
5. The root is always black
12
5 9
7
8
11
Red-Black Trees:
The Problem With Insertion
● Insert 11
■ Where does it go?
■ What color?
○ Can’t be red! (#3)
1. Every node is either red or black
2. Every leaf (NULL pointer) is black
3. If a node is red, both children are black
4. Every path from node to descendent leaf
contains the same number of black nodes
5. The root is always black
12
5 9
7
8
11
Red-Black Trees:
The Problem With Insertion
● Insert 11
■ Where does it go?
■ What color?
○ Can’t be red! (#3)
○ Can’t be black! (#4)
1. Every node is either red or black
2. Every leaf (NULL pointer) is black
3. If a node is red, both children are black
4. Every path from node to descendent leaf
contains the same number of black nodes
5. The root is always black
12
5 9
7
8
11
Red-Black Trees:
The Problem With Insertion
● Insert 11
■ Where does it go?
■ What color?
○ Solution:
recolor the tree
1. Every node is either red or black
2. Every leaf (NULL pointer) is black
3. If a node is red, both children are black
4. Every path from node to descendent leaf
contains the same number of black nodes
5. The root is always black
12
5 9
7
8
11
Red-Black Trees:
The Problem With Insertion
● Insert 10
■ Where does it go?
1. Every node is either red or black
2. Every leaf (NULL pointer) is black
3. If a node is red, both children are black
4. Every path from node to descendent leaf
contains the same number of black nodes
5. The root is always black
12
5 9
7
8
11
Red-Black Trees:
The Problem With Insertion
● Insert 10
■ Where does it go?
■ What color?
1. Every node is either red or black
2. Every leaf (NULL pointer) is black
3. If a node is red, both children are black
4. Every path from node to descendent leaf
contains the same number of black nodes
5. The root is always black
12
5 9
7
8
11
10
Red-Black Trees:
The Problem With Insertion
● Insert 10
■ Where does it go?
■ What color?
○ A: no color! Tree
is too imbalanced
○ Must change tree structure
to allow recoloring
■ Goal: restructure tree in
O(lg n) time
12
5 9
7
8
11
10
RB Trees: Rotation
● Our basic operation for changing tree structure
is called rotation:
● Does rotation preserve inorder key ordering?
● What would the code for rightRotate()
actually do?
y
x C
A B
x
A y
B C
rightRotate(y)
leftRotate(x)
rightRotate(y)
RB Trees: Rotation
● Answer: A lot of pointer manipulation
■ x keeps its left child
■ y keeps its right child
■ x’s right child becomes y’s left child
■ x’s and y’s parents change
● What is the running time?
y
x C
A B
x
A y
B C
Rotation Example
● Rotate left about 9:
12
5 9
7
8
11
Rotation Example
● Rotate left about 9:
5 12
7
9
118
Red-Black Trees: Insertion
● Insertion: the basic idea
■ Insert x into tree, color x red
■ Only r-b property 3 might be violated (if p[x] red)
○ If so, move violation up tree until a place is found
where it can be fixed
■ Total time will be O(lg n)
rbInsert(x)
treeInsert(x);
x->color = RED;
// Move violation of #3 up tree, maintaining #4 as invariant:
while (x!=root && x->p->color == RED)
if (x->p == x->p->p->left)
y = x->p->p->right;
if (y->color == RED)
x->p->color = BLACK;
y->color = BLACK;
x->p->p->color = RED;
x = x->p->p;
else // y->color == BLACK
if (x == x->p->right)
x = x->p;
leftRotate(x);
x->p->color = BLACK;
x->p->p->color = RED;
rightRotate(x->p->p);
else // x->p == x->p->p->right
(same as above, but with
“right” & “left” exchanged)
Case 1
Case 2
Case 3
rbInsert(x)
treeInsert(x);
x->color = RED;
// Move violation of #3 up tree, maintaining #4 as invariant:
while (x!=root && x->p->color == RED)
if (x->p == x->p->p->left)
y = x->p->p->right;
if (y->color == RED)
x->p->color = BLACK;
y->color = BLACK;
x->p->p->color = RED;
x = x->p->p;
else // y->color == BLACK
if (x == x->p->right)
x = x->p;
leftRotate(x);
x->p->color = BLACK;
x->p->p->color = RED;
rightRotate(x->p->p);
else // x->p == x->p->p->right
(same as above, but with
“right” & “left” exchanged)
Case 1: uncle is RED
Case 2
Case 3
RB Insert: Case 1
if (y->color == RED)
x->p->color = BLACK;
y->color = BLACK;
x->p->p->color = RED;
x = x->p->p;
● Case 1: “uncle” is red
● In figures below, all ∆’s are
equal-black-height subtrees
C
A D
∆ B
∆ ∆
∆ ∆
C
A D
∆ B
∆ ∆
∆ ∆x
y
new x
Change colors of some nodes, preserving #4: all downward paths have equal b.h.
The while loop now continues with x’s grandparent as the new x
case 1
B
∆ ∆
x
RB Insert: Case 1
if (y->color == RED)
x->p->color = BLACK;
y->color = BLACK;
x->p->p->color = RED;
x = x->p->p;
● Case 1: “uncle” is red
● In figures below, all ∆’s are
equal-black-height subtrees
C
A D
∆ ∆ ∆
C
A D
∆ ∆
y
new x
Same action whether x is a left or a right child
B
∆ ∆
x ∆
case 1
B
∆ ∆
x
RB Insert: Case 2
if (x == x->p->right)
x = x->p;
leftRotate(x);
// continue with case 3 code
● Case 2:
■ “Uncle” is black
■ Node x is a right child
● Transform to case 3 via a
left-rotation
C
A ∆
C
By
A
∆ ∆
x ∆
case 2
∆
y∆
Transform case 2 into case 3 (x is left child) with a left rotation
This preserves property 4: all downward paths contain same number of black nodes
RB Insert: Case 3
x->p->color = BLACK;
x->p->p->color = RED;
rightRotate(x->p->p);
● Case 3:
■ “Uncle” is black
■ Node x is a left child
● Change colors; rotate right
B
Ax
∆
case 3
C
B
A
∆ ∆
x ∆
y∆ C
∆ ∆∆
Perform some color changes and do a right rotation
Again, preserves property 4: all downward paths contain same number of black nodes
RB Insert: Cases 4-6
● Cases 1-3 hold if x’s parent is a left child
● If x’s parent is a right child, cases 4-6 are
symmetric (swap left for right)
Red-Black Trees: Deletion
● And you thought insertion was tricky…
● We will not cover RB delete in class
■ You should read section 14.4 on your own
■ Read for the overall picture, not the details
The End
● Coming up:
■ Skip lists
■ Hash tables

More Related Content

What's hot

What's hot (20)

Trees (data structure)
Trees (data structure)Trees (data structure)
Trees (data structure)
 
Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures
 
Tree - Data Structure
Tree - Data StructureTree - Data Structure
Tree - Data Structure
 
Hashing Technique In Data Structures
Hashing Technique In Data StructuresHashing Technique In Data Structures
Hashing Technique In Data Structures
 
linked list in data structure
linked list in data structure linked list in data structure
linked list in data structure
 
Binary search tree(bst)
Binary search tree(bst)Binary search tree(bst)
Binary search tree(bst)
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Binary Tree Traversal
Binary Tree TraversalBinary Tree Traversal
Binary Tree Traversal
 
Splay Tree
Splay TreeSplay Tree
Splay Tree
 
Binary tree
Binary treeBinary tree
Binary tree
 
Graph traversals in Data Structures
Graph traversals in Data StructuresGraph traversals in Data Structures
Graph traversals in Data Structures
 
AVL Tree Data Structure
AVL Tree Data StructureAVL Tree Data Structure
AVL Tree Data Structure
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
 
AVL Tree in Data Structure
AVL Tree in Data Structure AVL Tree in Data Structure
AVL Tree in Data Structure
 
Red black tree
Red black treeRed black tree
Red black tree
 
Tree and graph
Tree and graphTree and graph
Tree and graph
 
Circular link list.ppt
Circular link list.pptCircular link list.ppt
Circular link list.ppt
 
Tree Traversal
Tree TraversalTree Traversal
Tree Traversal
 
Bfs and Dfs
Bfs and DfsBfs and Dfs
Bfs and Dfs
 

Similar to Red black tree

lecture 14
lecture 14lecture 14
lecture 14
sajinsc
 
anastasio-red-black-trees-1-1-091222204455-phpapp02.pdf
anastasio-red-black-trees-1-1-091222204455-phpapp02.pdfanastasio-red-black-trees-1-1-091222204455-phpapp02.pdf
anastasio-red-black-trees-1-1-091222204455-phpapp02.pdf
AayushAdhikari27
 
Unit 2 ADvanced Data Sturctures and Algorithms Red-black_trees.ppt
Unit 2 ADvanced Data Sturctures and Algorithms Red-black_trees.pptUnit 2 ADvanced Data Sturctures and Algorithms Red-black_trees.ppt
Unit 2 ADvanced Data Sturctures and Algorithms Red-black_trees.ppt
Sheba41
 
Advanced data structures and implementation
Advanced data structures and implementationAdvanced data structures and implementation
Advanced data structures and implementation
Umang Gupta
 

Similar to Red black tree (20)

lecture 14
lecture 14lecture 14
lecture 14
 
anastasio-red-black-trees-1-1-091222204455-phpapp02.pdf
anastasio-red-black-trees-1-1-091222204455-phpapp02.pdfanastasio-red-black-trees-1-1-091222204455-phpapp02.pdf
anastasio-red-black-trees-1-1-091222204455-phpapp02.pdf
 
Red Black Trees
Red Black TreesRed Black Trees
Red Black Trees
 
Unit 2 ADvanced Data Sturctures and Algorithms Red-black_trees.ppt
Unit 2 ADvanced Data Sturctures and Algorithms Red-black_trees.pptUnit 2 ADvanced Data Sturctures and Algorithms Red-black_trees.ppt
Unit 2 ADvanced Data Sturctures and Algorithms Red-black_trees.ppt
 
lecture14.ppt
lecture14.pptlecture14.ppt
lecture14.ppt
 
Advanced data structures and implementation
Advanced data structures and implementationAdvanced data structures and implementation
Advanced data structures and implementation
 
Red black trees
Red black treesRed black trees
Red black trees
 
Lec14
Lec14Lec14
Lec14
 
Balanced Tree(AVL Tree,Red Black Tree)
Balanced Tree(AVL Tree,Red Black Tree)Balanced Tree(AVL Tree,Red Black Tree)
Balanced Tree(AVL Tree,Red Black Tree)
 
Balanced Tree (AVL Tree & Red-Black Tree)
Balanced Tree (AVL Tree & Red-Black Tree)Balanced Tree (AVL Tree & Red-Black Tree)
Balanced Tree (AVL Tree & Red-Black Tree)
 
16 rbtrees
16 rbtrees16 rbtrees
16 rbtrees
 
Red black trees
Red black treesRed black trees
Red black trees
 
Data structure
Data structureData structure
Data structure
 
Red black trees
Red black treesRed black trees
Red black trees
 
Red blacktrees
Red blacktreesRed blacktrees
Red blacktrees
 
Cse 225 rbt_red_black_tree
Cse 225 rbt_red_black_treeCse 225 rbt_red_black_tree
Cse 225 rbt_red_black_tree
 
6_1 (1).ppt
6_1 (1).ppt6_1 (1).ppt
6_1 (1).ppt
 
rbtrees.ppt
rbtrees.pptrbtrees.ppt
rbtrees.ppt
 
Red-black trees
Red-black treesRed-black trees
Red-black trees
 
Red black tree in data structure
Red black tree in data structureRed black tree in data structure
Red black tree in data structure
 

More from Rajendran

More from Rajendran (20)

Element distinctness lower bounds
Element distinctness lower boundsElement distinctness lower bounds
Element distinctness lower bounds
 
Scheduling with Startup and Holding Costs
Scheduling with Startup and Holding CostsScheduling with Startup and Holding Costs
Scheduling with Startup and Holding Costs
 
Divide and conquer surfing lower bounds
Divide and conquer  surfing lower boundsDivide and conquer  surfing lower bounds
Divide and conquer surfing lower bounds
 
Hash table
Hash tableHash table
Hash table
 
Medians and order statistics
Medians and order statisticsMedians and order statistics
Medians and order statistics
 
Proof master theorem
Proof master theoremProof master theorem
Proof master theorem
 
Recursion tree method
Recursion tree methodRecursion tree method
Recursion tree method
 
Recurrence theorem
Recurrence theoremRecurrence theorem
Recurrence theorem
 
Master method
Master method Master method
Master method
 
Master method theorem
Master method theoremMaster method theorem
Master method theorem
 
Hash tables
Hash tablesHash tables
Hash tables
 
Lower bound
Lower boundLower bound
Lower bound
 
Master method theorem
Master method theoremMaster method theorem
Master method theorem
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
Longest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm AnalysisLongest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm Analysis
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm Analysis
 
Average case Analysis of Quicksort
Average case Analysis of QuicksortAverage case Analysis of Quicksort
Average case Analysis of Quicksort
 
Np completeness
Np completenessNp completeness
Np completeness
 
computer languages
computer languagescomputer languages
computer languages
 
proving non-computability
proving non-computabilityproving non-computability
proving non-computability
 

Recently uploaded

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Recently uploaded (20)

Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 

Red black tree

  • 2. Red-Black Trees ● Red-black trees: ■ Binary search trees augmented with node color ■ Operations designed to guarantee that the height h = O(lg n) ● First: describe the properties of red-black trees ● Then: prove that these guarantee h = O(lg n) ● Finally: describe operations on red-black trees
  • 3. Red-Black Properties ● The red-black properties: 1. Every node is either red or black 2. Every leaf (NULL pointer) is black ○ Note: this means every “real” node has 2 children 3. If a node is red, both children are black ○ Note: can’t have 2 consecutive reds on a path 4. Every path from node to descendent leaf contains the same number of black nodes 5. The root is always black
  • 4. Red-Black Trees ● Put example on board and verify properties: 1. Every node is either red or black 2. Every leaf (NULL pointer) is black 3. If a node is red, both children are black 4. Every path from node to descendent leaf contains the same number of black nodes 5. The root is always black ● black-height: # black nodes on path to leaf ■ Label example with h and bh values
  • 5. David Luebke 5 02/10/17 Height of Red-Black Trees ● What is the minimum black-height of a node with height h? ● A: a height-h node has black-height ≥ h/2 ● Theorem: A red-black tree with n internal nodes has height h ≤ 2 lg(n + 1) ● How do you suppose we’ll prove this?
  • 6. RB Trees: Proving Height Bound ● Prove: n-node RB tree has height h ≤ 2 lg(n+1) ● Claim: A subtree rooted at a node x contains at least 2bh(x) - 1 internal nodes ■ Proof by induction on height h ■ Base step: x has height 0 (i.e., NULL leaf node) ○ What is bh(x)?
  • 7. RB Trees: Proving Height Bound ● Prove: n-node RB tree has height h ≤ 2 lg(n+1) ● Claim: A subtree rooted at a node x contains at least 2bh(x) - 1 internal nodes ■ Proof by induction on height h ■ Base step: x has height 0 (i.e., NULL leaf node) ○ What is bh(x)? ○ A: 0 ○ So…subtree contains 2bh(x) - 1 = 20 - 1 = 0 internal nodes (TRUE)
  • 8. RB Trees: Proving Height Bound ● Inductive proof that subtree at node x contains at least 2bh(x) - 1 internal nodes ■ Inductive step: x has positive height and 2 children ○ Each child has black-height of bh(x) or bh(x)-1 (Why?) ○ The height of a child = (height of x) - 1 ○ So the subtrees rooted at each child contain at least 2bh(x)-1 - 1 internal nodes ○ Thus subtree at x contains (2bh(x)-1 - 1) + (2bh(x)-1 - 1) + 1 = 2•2bh(x)-1 - 1 = 2bh(x) - 1 nodes
  • 9. RB Trees: Proving Height Bound ● Thus at the root of the red-black tree: n ≥ 2bh(root) - 1 (Why?) n ≥ 2h/2 - 1 (Why?) lg(n+1) ≥ h/2 (Why?) h ≤ 2 lg(n + 1) (Why?) Thus h = O(lg n)
  • 10. RB Trees: Worst-Case Time ● So we’ve proved that a red-black tree has O(lg n) height ● Corollary: These operations take O(lg n) time: ■ Minimum(), Maximum() ■ Successor(), Predecessor() ■ Search() ● Insert() and Delete(): ■ Will also take O(lg n) time ■ But will need special care since they modify tree
  • 11. Red-Black Trees: An Example ● Color this tree: 7 5 9 1212 5 9 7 Red-black properties: 1. Every node is either red or black 2. Every leaf (NULL pointer) is black 3. If a node is red, both children are black 4. Every path from node to descendent leaf contains the same number of black nodes 5. The root is always black
  • 12. ● Insert 8 ■ Where does it go? Red-Black Trees: The Problem With Insertion 12 5 9 7 1. Every node is either red or black 2. Every leaf (NULL pointer) is black 3. If a node is red, both children are black 4. Every path from node to descendent leaf contains the same number of black nodes 5. The root is always black
  • 13. ● Insert 8 ■ Where does it go? ■ What color should it be? Red-Black Trees: The Problem With Insertion 12 5 9 7 8 1. Every node is either red or black 2. Every leaf (NULL pointer) is black 3. If a node is red, both children are black 4. Every path from node to descendent leaf contains the same number of black nodes 5. The root is always black
  • 14. ● Insert 8 ■ Where does it go? ■ What color should it be? Red-Black Trees: The Problem With Insertion 12 5 9 7 8 1. Every node is either red or black 2. Every leaf (NULL pointer) is black 3. If a node is red, both children are black 4. Every path from node to descendent leaf contains the same number of black nodes 5. The root is always black
  • 15. Red-Black Trees: The Problem With Insertion ● Insert 11 ■ Where does it go? 1. Every node is either red or black 2. Every leaf (NULL pointer) is black 3. If a node is red, both children are black 4. Every path from node to descendent leaf contains the same number of black nodes 5. The root is always black 12 5 9 7 8
  • 16. Red-Black Trees: The Problem With Insertion ● Insert 11 ■ Where does it go? ■ What color? 1. Every node is either red or black 2. Every leaf (NULL pointer) is black 3. If a node is red, both children are black 4. Every path from node to descendent leaf contains the same number of black nodes 5. The root is always black 12 5 9 7 8 11
  • 17. Red-Black Trees: The Problem With Insertion ● Insert 11 ■ Where does it go? ■ What color? ○ Can’t be red! (#3) 1. Every node is either red or black 2. Every leaf (NULL pointer) is black 3. If a node is red, both children are black 4. Every path from node to descendent leaf contains the same number of black nodes 5. The root is always black 12 5 9 7 8 11
  • 18. Red-Black Trees: The Problem With Insertion ● Insert 11 ■ Where does it go? ■ What color? ○ Can’t be red! (#3) ○ Can’t be black! (#4) 1. Every node is either red or black 2. Every leaf (NULL pointer) is black 3. If a node is red, both children are black 4. Every path from node to descendent leaf contains the same number of black nodes 5. The root is always black 12 5 9 7 8 11
  • 19. Red-Black Trees: The Problem With Insertion ● Insert 11 ■ Where does it go? ■ What color? ○ Solution: recolor the tree 1. Every node is either red or black 2. Every leaf (NULL pointer) is black 3. If a node is red, both children are black 4. Every path from node to descendent leaf contains the same number of black nodes 5. The root is always black 12 5 9 7 8 11
  • 20. Red-Black Trees: The Problem With Insertion ● Insert 10 ■ Where does it go? 1. Every node is either red or black 2. Every leaf (NULL pointer) is black 3. If a node is red, both children are black 4. Every path from node to descendent leaf contains the same number of black nodes 5. The root is always black 12 5 9 7 8 11
  • 21. Red-Black Trees: The Problem With Insertion ● Insert 10 ■ Where does it go? ■ What color? 1. Every node is either red or black 2. Every leaf (NULL pointer) is black 3. If a node is red, both children are black 4. Every path from node to descendent leaf contains the same number of black nodes 5. The root is always black 12 5 9 7 8 11 10
  • 22. Red-Black Trees: The Problem With Insertion ● Insert 10 ■ Where does it go? ■ What color? ○ A: no color! Tree is too imbalanced ○ Must change tree structure to allow recoloring ■ Goal: restructure tree in O(lg n) time 12 5 9 7 8 11 10
  • 23. RB Trees: Rotation ● Our basic operation for changing tree structure is called rotation: ● Does rotation preserve inorder key ordering? ● What would the code for rightRotate() actually do? y x C A B x A y B C rightRotate(y) leftRotate(x)
  • 24. rightRotate(y) RB Trees: Rotation ● Answer: A lot of pointer manipulation ■ x keeps its left child ■ y keeps its right child ■ x’s right child becomes y’s left child ■ x’s and y’s parents change ● What is the running time? y x C A B x A y B C
  • 25. Rotation Example ● Rotate left about 9: 12 5 9 7 8 11
  • 26. Rotation Example ● Rotate left about 9: 5 12 7 9 118
  • 27. Red-Black Trees: Insertion ● Insertion: the basic idea ■ Insert x into tree, color x red ■ Only r-b property 3 might be violated (if p[x] red) ○ If so, move violation up tree until a place is found where it can be fixed ■ Total time will be O(lg n)
  • 28. rbInsert(x) treeInsert(x); x->color = RED; // Move violation of #3 up tree, maintaining #4 as invariant: while (x!=root && x->p->color == RED) if (x->p == x->p->p->left) y = x->p->p->right; if (y->color == RED) x->p->color = BLACK; y->color = BLACK; x->p->p->color = RED; x = x->p->p; else // y->color == BLACK if (x == x->p->right) x = x->p; leftRotate(x); x->p->color = BLACK; x->p->p->color = RED; rightRotate(x->p->p); else // x->p == x->p->p->right (same as above, but with “right” & “left” exchanged) Case 1 Case 2 Case 3
  • 29. rbInsert(x) treeInsert(x); x->color = RED; // Move violation of #3 up tree, maintaining #4 as invariant: while (x!=root && x->p->color == RED) if (x->p == x->p->p->left) y = x->p->p->right; if (y->color == RED) x->p->color = BLACK; y->color = BLACK; x->p->p->color = RED; x = x->p->p; else // y->color == BLACK if (x == x->p->right) x = x->p; leftRotate(x); x->p->color = BLACK; x->p->p->color = RED; rightRotate(x->p->p); else // x->p == x->p->p->right (same as above, but with “right” & “left” exchanged) Case 1: uncle is RED Case 2 Case 3
  • 30. RB Insert: Case 1 if (y->color == RED) x->p->color = BLACK; y->color = BLACK; x->p->p->color = RED; x = x->p->p; ● Case 1: “uncle” is red ● In figures below, all ∆’s are equal-black-height subtrees C A D ∆ B ∆ ∆ ∆ ∆ C A D ∆ B ∆ ∆ ∆ ∆x y new x Change colors of some nodes, preserving #4: all downward paths have equal b.h. The while loop now continues with x’s grandparent as the new x case 1
  • 31. B ∆ ∆ x RB Insert: Case 1 if (y->color == RED) x->p->color = BLACK; y->color = BLACK; x->p->p->color = RED; x = x->p->p; ● Case 1: “uncle” is red ● In figures below, all ∆’s are equal-black-height subtrees C A D ∆ ∆ ∆ C A D ∆ ∆ y new x Same action whether x is a left or a right child B ∆ ∆ x ∆ case 1
  • 32. B ∆ ∆ x RB Insert: Case 2 if (x == x->p->right) x = x->p; leftRotate(x); // continue with case 3 code ● Case 2: ■ “Uncle” is black ■ Node x is a right child ● Transform to case 3 via a left-rotation C A ∆ C By A ∆ ∆ x ∆ case 2 ∆ y∆ Transform case 2 into case 3 (x is left child) with a left rotation This preserves property 4: all downward paths contain same number of black nodes
  • 33. RB Insert: Case 3 x->p->color = BLACK; x->p->p->color = RED; rightRotate(x->p->p); ● Case 3: ■ “Uncle” is black ■ Node x is a left child ● Change colors; rotate right B Ax ∆ case 3 C B A ∆ ∆ x ∆ y∆ C ∆ ∆∆ Perform some color changes and do a right rotation Again, preserves property 4: all downward paths contain same number of black nodes
  • 34. RB Insert: Cases 4-6 ● Cases 1-3 hold if x’s parent is a left child ● If x’s parent is a right child, cases 4-6 are symmetric (swap left for right)
  • 35. Red-Black Trees: Deletion ● And you thought insertion was tricky… ● We will not cover RB delete in class ■ You should read section 14.4 on your own ■ Read for the overall picture, not the details
  • 36. The End ● Coming up: ■ Skip lists ■ Hash tables