Red-Black Tree
Insert
–
Pseudocode
1insert v like in a normal BST and colour it RED2while v's parent is red:3 uncle ← the parent's sibling4 uncle red: parent and uncle → black, grandparent → red; v ← grandparent5 v is an inner child: rotate at the parent so v becomes an outer child6 rotate at the grandparent; swap the colours of parent and grandparent7colour the root black
Comparisons
0
Rotations
0
Black height
0
unclerole in the current fix-upnode being checked
What is a Red-Black Tree?
A red-black tree is a binary search tree where every node is coloured red or black, and the colours follow a few rules: the root is black, a red node never has a red child, and every path down to an empty leaf has the same number of black nodes (the black height).
Those rules guarantee the longest path is at most twice the shortest, so the tree stays O(log n) tall. It is a little less strictly balanced than an AVL tree, but needs fewer rotations, which is why it powers std::map, Java's TreeMap and the Linux scheduler.
New nodes are red; fix any red-red pair by recolouring or rotating.
Using the Visualizer
- • Insert a value: it arrives red. Tags (parent, uncle, grand) show the nodes the fix-up looks at.
- • A red uncle means only recolouring; a black uncle means one or two rotations.
- • Press Insert in order to watch 10, 20, …, 80 stay balanced.
- • Delete a black node to see the four double-black cases.
How It Works
Insert: add a red leaf
Red doesn't change any black height, so only rule 2 (no red-red) can break.
Red uncle: recolour
Parent and uncle turn black, grandparent turns red; continue from the grandparent.
Black uncle: rotate
Inner child: rotate at the parent first. Then rotate at the grandparent and swap colours.
Delete: extra black
Removing a black node leaves a path short of one black; four sibling cases recolour and rotate to repair it.
Implementation
Properties & Complexity
Time Complexity
- • Search, insert, delete: O(log n) worst case
- • Rotations: at most 2 per insert, 3 per delete
Space & Properties
- • Space: O(n), one colour bit per node
- • Height: at most 2·log₂(n + 1)
Where It Is Used
- • C++ std::map / std::set, Java TreeMap / TreeSet
- • Linux kernel: the CFS scheduler and memory areas
- • Databases and in-memory ordered indexes
Limitations
- • Complex delete with many cases
- • Slightly taller than AVL trees, so lookups can be a bit slower