UPI Study › Courses › Data Structures and Algorithms › Free lessons › Lesson 15.4 Free with a free account
Balanced Trees Compared: Red-Black Trees and TreeMap
Data Structures and Algorithms · Chapter 15: Balanced Search TreesSection 15.4 · lesson 66 of 879 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Data Structures and Algorithms.
Lesson complete
Earn the 3 college credits for Data Structures and Algorithms
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Elementary Sorts: Bubble Sort and Selection Sort →← Multiway Search Trees: 2-3 Trees, 2-4 Trees, and B-TreesNext lesson: Elementary Sorts: Bubble Sort and Selection Sort →
In this lesson
Red-black trees as 2-4 trees, compared with AVL trees and TreeMap.
- Map each red-black tree rule to a matching 2-4 tree rule
- Trace red-black insertion with recoloring and rotations on sorted keys
- Compare red-black and AVL trees on height, search cost and deletion repairs
- Use TreeMap and TreeSet navigation methods, range views and comparators correctly
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (1,326 words). Read along, or search it.
Opening Question
What Sits Inside TreeMap
Java programs rarely build their own balanced tree. They reach for TreeMap, and its documentation says what's inside: a red-black tree. Red-black trees look strange at first, with every node colored red or black. But they're an old friend in disguise: a 2-4 tree, written as a binary tree. So first the colors, then red-black trees against AVL trees on real measurements, and then TreeMap and TreeSet at work.
Encoding
Wide Nodes as Red and Black Groups
A 2-4 tree node holds one to three keys, and all its leaves sit at one depth. Wide nodes are awkward to code. So a red-black tree writes each wide node as a small group of binary nodes. A black node starts a group. A red node is glued to the black node above it. A 2-node is a single black node. A 3-node is a black node with one red child, on either side. And a 4-node is a black node with two red children. The middle key sits on the black node.
Rules
Red-Black Rules as 2-4 Rules
Every red-black rule is a 2-4 rule in disguise. The root is black. And a red node never has a red child, so a group holds at most three keys. Every path from the root down to a missing child passes the same number of black nodes. That count is the 2-4 tree's depth, called the black height. And a new node starts red: a new key joins an existing group, just as a key joins a 2-4 leaf. Reds can't stack, so the longest path is at most twice the shortest. The height is at most two times log base two of the quantity n plus one.
In Code
Insertion and the Balance Step
Here's insertion in Java. It inserts like a plain search tree, and every new node starts red. Then, on the way back up, balance looks for a black node over a red child over a red grandchild. That's a group of three keys in the wrong shape. There are four possible layouts. In each one, the middle key moves up as a red node, and the other two become separate black groups. That's a 2-4 node splitting, written with pointers. And after every insert, the root is painted black.
Worked Example
Inserting Keys in Sorted Order
Run it, inserting 10, 20, 30, 40, and 50, in order. Each line shows the tree, with R for red and B for black, and then its 2-4 view. At 30, the three keys would form a chain. The repair splits them: 20 on top, 10 and 30 below, all black. At 50, the red 40 has joined 20's group. In 2-4 terms, the root holds 20 and 40, over three leaves. Then 10 through 100, in sorted order. A plain tree would be a chain of ten levels. This one has five, and every 2-4 leaf sits on level three.
Measured Comparison
Red-Black Versus AVL Trees
How do red-black trees compare with AVL trees? A test built both from the same keys, sorted and random, up to 100,000. The AVL tree is flatter. With 100,000 sorted keys, it had 17 levels, against 22 for the red-black tree. But the average search was almost identical: 15.69 steps against 15.72. Most nodes aren't on the longest path. Both did about one repair per insert on sorted keys. Red-black trees win on deletes: at most three rotations, where an AVL delete may rotate at every level.
Decision Guide
AVL, Red-Black, B-Tree or Hash Table
So which structure fits which job? Many lookups and few updates, in memory: an AVL tree saves a few steps on the worst lookups. Frequent inserts and deletes, in memory: a red-black tree, which in Java usually means TreeMap. Data too large for memory, stored in disk blocks: a B-tree, with one wide node per block read. And if only exact lookups matter, with no order at all: a hash table.
Java Example
A Day of Bookings in a TreeMap
Now TreeMap in practice. This map keeps a day's bookings, with times written as numbers, so 1130 means half past eleven. Printing the map lists the keys in sorted order, whatever order they were put in. floorKey of 1200 is the latest start at noon or before: 1130. ceilingKey of 1200 is the first start at noon or after: 1400. subMap from 1000 to 1500 includes its start, and excludes its end. headMap of 1130 holds everything before 1130. And pollFirstEntry removes and returns the smallest entry. Each of these calls costs order log n.
Navigation Methods
Lower, Floor, Ceiling and Higher
The four navigation methods are easy to mix up. Lower is the largest key strictly below the query. Floor is the largest key at or below it. Ceiling is the smallest key at or above the query, and higher is the smallest strictly above it. So floor and ceiling may return the query itself, and lower and higher always skip past it. In the set 10 to 50, a query of 35 gives 30 for both lower and floor. A query of 40 is stored. Floor and ceiling return 40 itself, while lower drops to 30, and higher climbs to 50.
Quick Check
Navigation at the Edges
Quick check, with the same five keys. This program prints lower of 10, floor of 45, ceiling of 45, and higher of 50. What does it print? Pause and predict. It prints null, 40, 50, null. Nothing is below 10, so lower of 10 is null. Lower never returns the query itself. 45 isn't stored, so floor and ceiling are its neighbors, 40 and 50. And nothing is above 50, so higher of 50 is null too.
Range Views
SubMap Is a Window, Not a Copy
Range methods like subMap don't copy anything. They return a view: a window onto the original map. Here the window covers keys 20 through 40. Passing true for both ends includes both of them. Clear the window, and those three entries vanish from the map itself. If a range must stay separate, copy it into a new TreeMap first.
Common Surprise
The Comparator Decides Duplicates
Here's a surprise. A TreeSet or TreeMap never calls equals. Two keys count as the same whenever the comparator returns zero for them. With natural string order, capital letters sort first. So APPLE comes before Banana, and apple is a different key. The size is four. With a case-insensitive comparator, apple and APPLE compare as equal. The set keeps the first one it saw, so its size is three. A map works the same way. Put Tree, then TREE: the second put replaces the value, and the key stays as first written.
Quick Check
A Set Ordered by Length
Quick check, with a new comparator. This set orders words by their length. Five words are added: pear, fig, kiwi, apple, and plum. What gets printed? Pause and predict. It prints fig, pear, apple. The comparator looks only at length, so kiwi and plum tie with pear. It returns zero, and the set treats them as duplicates. A duplicate add is simply ignored, so the first four-letter word, pear, stays. Alphabetical order never comes into it. To keep all five, the comparator must break ties, for example by comparing the words themselves next.
Robustness
Sorted Keys Without Stack Overflow
Remember the plain search tree that ran out of call stack on 200,000 sorted keys? TreeMap takes the same keys without trouble. It rebalances as it goes, so its height stays logarithmic, and every put and get is a short walk.
Comparison
TreeMap Versus HashMap
Finally, TreeMap or HashMap? Put five names into each. The HashMap lists them in an order that Java doesn't promise. The TreeMap lists them alphabetically, every time. A HashMap's get and put take expected constant time. A TreeMap's take order log n, but it can answer floor, ceiling, and range questions. So use HashMap when only exact lookups matter, and TreeMap when the keys must stay in order, or nearby keys are needed.
Key Takeaways
Colors, Comparisons and TreeMap
To sum up. A red-black tree is a 2-4 tree in binary form. A black node starts a group, and red nodes join it. Equal black counts on every path keep the height under two log n. AVL trees are a little flatter, red-black trees repair less, and B-trees suit disks. TreeMap and TreeSet give sorted order, floor, ceiling, and range views, in order log n. And the comparator alone decides which keys count as duplicates.
About Data Structures and Algorithms at UPI Study
Data Structures and Algorithms (Computer Science 251) is a self-paced online course of 87 video lessons in 17 chapters, from Java and object-oriented design to arrays, linked lists, recursion, stacks and queues, trees, heaps, hash tables, sorting and graphs. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: Discrete Math vs Data Structures and Algorithms · Intro to Java vs Data Structures and Algorithms
Why take it here
Why students take Data Structures and Algorithms with UPI Study
Where the credit goes
Universities that work with NCCRS
Data Structures and Algorithms carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Balanced Trees Compared: Red-Black Trees and TreeMap
How is a red-black tree related to a 2-4 tree?
Is an AVL tree or a red-black tree better?
Why does Java's TreeMap use a red-black tree?
Why does a TreeSet with a comparator drop some elements?
About the Data Structures and Algorithms course
How many college credits is Data Structures and Algorithms?
How much does Data Structures and Algorithms cost and what is included?
Which universities accept UPI Study credits?
How long does Data Structures and Algorithms take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Data Structures and Algorithms.
87 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →