CS 367 Introduction to Data Structures Lecture 9.

Slides:



Advertisements
Similar presentations
1 AVL Trees (10.2) CSE 2011 Winter April 2015.
Advertisements

Chapter 4: Trees Part II - AVL Tree
Topic 23 Red Black Trees "People in every direction No words exchanged No time to exchange And all the little ants are marching Red and black antennas.
CSC 213 – Large Scale Programming. Red-Black Tree Properties black  Root Property: Root node painted black black  External Property: Leaves are painted.
AA Trees another alternative to AVL trees. Balanced Binary Search Trees A Binary Search Tree (BST) of N nodes is balanced if height is in O(log N) A balanced.
Balanced Binary Search Trees
November 5, Algorithms and Data Structures Lecture VIII Simonas Šaltenis Nykredit Center for Database Research Aalborg University
A balanced life is a prefect life.
1 /26 Red-black tree properties Every node in a red-black tree is either black or red Every null leaf is black No path from a leaf to a root can have two.
1 Binary Search Trees Implementing Balancing Operations –AVL Trees –Red/Black Trees Reading:
1 Red-Black Trees. 2 Black-Height of the tree = 4.
1 Red-Black Trees. 2 Black-Height of the tree = 4.
1 COSC 2P03 Lecture #5 – Trees Part III, Heaps. 2 Today Take up the quiz Assignment Questions Red-Black Trees Binary Heaps Heap sort D-Heaps, Leftist.
Dynamic Set AVL, RB Trees G.Kamberova, Algorithms Dynamic Set ADT Balanced Trees Gerda Kamberova Department of Computer Science Hofstra University.
Chapter 13 Binary Search Trees. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Define a binary search tree abstract.
1 /26 Red-black tree properties Every node in a red-black tree is either black or red Every null leaf is black No path from a leaf to a root can have two.
CSC 212 Lecture 19: Splay Trees, (2,4) Trees, and Red-Black Trees.
Advanced Trees Part III Briana B. Morrison Adapted from Alan Eugenio & William J. Collins.
CS 61B Data Structures and Programming Methodology Aug 11, 2008 David Sun.
Balanced Search Trees Chapter 27 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Course: Programming II - Abstract Data Types Red-Black TreesSlide Number 1 Balanced Search Trees Binary Search Tree data structures can allow insertion,
Analysis of Red-Black Tree Because of the rules of the Red-Black tree, its height is at most 2log(N + 1). Meaning that it is a balanced tree Time Analysis:
10/20/2015 2:03 PMRed-Black Trees v z. 10/20/2015 2:03 PMRed-Black Trees2 Outline and Reading From (2,4) trees to red-black trees (§9.5) Red-black.
© 2004 Goodrich, Tamassia Red-Black Trees v z.
Balanced Trees (AVL and RedBlack). Binary Search Trees Optimal Behavior ▫ O(log 2 N) – perfectly balanced tree (e.g. complete tree with all levels filled)
© 2004 Goodrich, Tamassia Red-Black Trees v z.
CS-2851 Dr. Mark L. Hornick 1 Okasaki’s Insertion Method for Red/Black balancing A step-by-step procedure for maintaining balance through application of.
CSIT 402 Data Structures II
Beyond (2,4) Trees What do we know about (2,4)Trees? Balanced
Min Chen School of Computer Science and Engineering Seoul National University Data Structure: Chapter 8.
Lecture 2 Red-Black Trees. 8/3/2007 UMBC CSMC 341 Red-Black-Trees-1 2 Red-Black Trees Definition: A red-black tree is a binary search tree in which: 
1 Data Structures and Algorithms Searching Red-Black and Other Dynamically BalancedTrees.
Fall 2006 CSC311: Data Structures 1 Chapter 10: Search Trees Objectives: Binary Search Trees: Search, update, and implementation AVL Trees: Properties.
3.1. Binary Search Trees   . Ordered Dictionaries Keys are assumed to come from a total order. Old operations: insert, delete, find, …
Binary Search Trees (BSTs) 18 February Binary Search Tree (BST) An important special kind of binary tree is the BST Each node stores some information.
CS 367 Introduction to Data Structures Lecture 7.
Red-Black Tree Insertion Start with binary search insertion, coloring the new node red NIL l Insert 18 NIL l NIL l 1315 NIL l
CS 367 Introduction to Data Structures Lecture 8.
CS 307 Fundamentals of Computer ScienceRed Black Trees 1 Topic 19 Red Black Trees "People in every direction No words exchanged No time to exchange And.
1 Binary Search Trees   . 2 Ordered Dictionaries Keys are assumed to come from a total order. New operations: closestKeyBefore(k) closestElemBefore(k)
1 Binary Search Trees  Average case and worst case Big O for –insertion –deletion –access  Balance is important. Unbalanced trees give worse than log.
Red-Black Trees Bottom-Up Deletion. Recall “ordinary” BST Delete 1.If vertex to be deleted is a leaf, just delete it. 2.If vertex to be deleted has just.
Keeping Binary Trees Sorted. Search trees Searching a binary tree is easy; it’s just a preorder traversal public BinaryTree findNode(BinaryTree node,
Red-Black Trees an alternative to AVL trees. Balanced Binary Search Trees A Binary Search Tree (BST) of N nodes is balanced if height is in O(log N) A.
1 Red-Black Trees. 2 A Red-Black Tree with NULLs shown Black-Height of the tree = 4.
Lecture 23 Red Black Tree Chapter 10 of textbook
AA Trees.
File Organization and Processing Week 3
Red-Black Trees v z Red-Black Trees Red-Black Trees
Red-Black Trees 5/17/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and.
Red-Black Trees 5/22/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and.
Balanced Trees (AVL and RedBlack)
Red-Black Trees.
Red-Black Trees v z Red-Black Trees 1 Red-Black Trees
Red-Black Trees Bottom-Up Deletion.
Red-Black Trees Bottom-Up Deletion.
TCSS 342, Winter 2006 Lecture Notes
Red-Black Trees v z Red-Black Trees 1 Red-Black Trees
Red-Black Trees v z /20/2018 7:59 AM Red-Black Trees
Red-Black Trees v z Red-Black Trees Red-Black Trees
Red-Black Trees Bottom-Up Deletion.
Topic 23 Red Black Trees "People in every direction No words exchanged No time to exchange And all the little ants are marching Red and Black.
Red-Black Trees v z /17/2019 4:20 PM Red-Black Trees
Red-Black Trees Bottom-Up Deletion.
Balanced binary search trees
(2,4) Trees /6/ :26 AM (2,4) Trees (2,4) Trees
Red-black tree properties
Red Black Trees Top-Down Deletion.
Red-Black Trees v z /6/ :10 PM Red-Black Trees
Presentation transcript:

CS 367 Introduction to Data Structures Lecture 9

Maps and Sets Java provides several “industrial- strength” implementations of maps and sets. Two of these, TreeSet and TreeMap, are implemented using BSTs.

A set simply keeps tract of what values are in the set. In Java, the Set interface is implemented. One use of a set is a simple spell- checker. It loads valid words into a set and checks spelling by checking membership in the valid word set. (More thorough checkers know about variations of a word, like plurals and tenses).

Set dictionary = new TreeSet (); Set misspelled = new TreeSet (); // Create a set of "good" words. while (...) { String goodWord =...; dictionary.add(goodWord); } // Look up various other words while (...) { String word =...; if (! dictionary.contains(word)) { misspelled.add(word); }

Maps are used to store information relating to a key value. The structure “maps” a key into a result. One application of a map is to count the number of times a word appears in a document. (This is similar to the “word-cloud” of project 3.)

public class CountWords { Map wordCount = new TreeMap ();... Scanner in = new Scanner(new File(args[0])); in.useDelimiter("\\W+");...

while (in.hasNext()) { String word = in.next(); Integer count = wordCount.get(word); if (count == null) { wordCount.put(word, 1); } else { wordCount.put(word, count + 1);} } for (String word : wordCount.keySet()) { System.out.println(word + " " + count.get(word)); } } // CountWords }

Unbalanced BSTs The fast access time offered by BSTs requires that the tree be balanced (or nearly so). An unbalanced tree can have paths lengths greater than O(log N).

Unfortunately, reasonable entry orders can lead to an unbalanced tree. Consier keys entered in alphabetic or numeric order. Consider keys 1, 2, 3, 4... :

Rebalancing a BST We’d like to rebalance a BST if it starts to become unbalanced. Red-black trees do this.

Red-Black Trees A red-black tree is simply a BST with one added property – a color (red or black). Informally, black nodes are the “core” or the tree – nearly balanced. Red nodes are newly added nodes. As the tree becomes unbalanced, nodes are recolored or restructured.

A red-black tree must satisfy the following rules: 1. (root property) The root of the red- black tree is black 2. (red property) The children of a red node are black. 3. (black property) The number of black nodes on the path from the root to any null child is the same.

A null child is simply a null value used to mark a null subtree.

In a red-black tree no path from the root to a leaf can have two consecutive red nodes. Why? Since all paths from the root to a null child have the same number of black nodes, no path from root to a null child can differ by more than a factor of two. Why?

A technical detail In a red-black tree, all null children are considered to be colored black:

Operations on Red-black Trees Operations like lookup or tree traversal that don’t add or remove nodes are entirely unchanged. Why?

Insertion into a Red-black Tree A simple special case: If the BST is empty, we insert the node as the root and color it black. Otherwise, we know the existing BST is non-empty and has a black root.

Insertion operation: 1. Use the BST insert algorithm to add K to the tree 2. Color the node containing K red 3. Restore red-black tree properties (if necessary)

We have just inserted K into a red-black tree. What can go wrong? K is red. If its parent is black, the BST is still valid! Why?

If K’s parent is red, we are in violation of the red property. We must restructure or recolor. Call K’s parent P. (It is red.) P must have a black parent (K’s grandparent) Why? Call the grandparent G.

P may have a sibling, S (G’s other child) or P may be an only child. If P is an only child, or S is black, we do restructuring. If S is red, we do recoloring.

Restructuring. Look at just the three nodes, K, P and G in the BST. Four structures are possible: K K K K K K K K P P P P P P P P

Each of K, P and G have a distinct key value. We’ll choose the middle value and restructure so that the middle value is the new parent of the other two nodes. Each of the 4 cases is detailed in the following slides.

Note the recoloring of the 3 nodes. Now it is a valid red-black tree. Why?

Note the recoloring of the 3 nodes. Now it is a valid red-black tree. Why?

Note the recoloring of the 3 nodes. Now it is a valid red-black tree. Why?

Note the recoloring of the 3 nodes. Now it is a valid red-black tree. Why?

Recoloring We know P and K are both red. If S, P’s sibling, is also red we do a recoloring – P and S become red:

The red-red conflict between P and K is resolved. Moreover, the count of black nodes is unchanged.

But, recoloring G to red might introduce a red-red conflict between G and its parent. If so, we just reapply the restructure/recolor rules to those two nodes and resolve the problem (working up the tree toward the root).

Insertion Example Recall that inserting keys in numeric or alphabetic order can create very unbalanced BSTs. For 1,2,3,4 we got:

Let’s do the same insertions using red- black trees. 1. We insert 1 as a red node. Since it is a root, it is immediately recolored to black: 1. Next we insert 2 as a red node (getting a valid red-black tree): 2 2

3. Next we add 3 as a red node getting an invalid red-black tree:

The tree is restructured, making 2 the new root:

4. Now 4 is inserted as a red node, creating an invalid red-black tree:

Since 1, 3 and 4 are all red, we do a recoloring. Nodes 1 and 3 become black. Node 2 becomes red, then is changed back to black because it is the root

5. Finally, 5 is added as a red node:

The 3 – 4– 5 subtree is restructured:

Class Participation Insert the following into a red-black tree: 7, 14, 18, 23, 1, 11, 20, 29, 25, 27

Complexity of Insertion into a Red-black Tree Insertion requires three steps: 1. An ordinary BST insertion. This is O(log n) if the tree is balanced. 2. Color new node red – O(1) time

3. Restore red-black properties (if needed). Restructuring is done at most once. It is O(1) since only a limited number of pointers are reset. Recoloring is also O(1) but may need to be repeated up the tree. Since the tree is balanced, at most O(log n) recolorings are needed. The overall complexity is therefore O(log n).

Deletion from Red-black Trees The delete operation is similar in feel to the insert operation, but more complicated. You will not be expected to know its operation.