The user wants a Red-Black Tree implementation.
This is a classic computer science data structure.
I need to provide code (likely in Python or C++) and an explanation.
The core operations are insertion and deletion, including the fix-up routines (rotations and recoloring).
Key constraints/properties of Red-Black Trees:
Every node is either Red or Black.
The root is Black.
All leaves (NIL) are Black.
If a node is Red, both children are Black.
Every path from a node to its descendant leaves contains the same number of Black nodes.
Operations to implement:
Insertion:
Standard BST insertion.
Color the new node Red.
Fix violations (Red-Red conflict).
Case 1: Uncle is Red (Recolor).
Case 2: Uncle is Black (Rotate and Recolor).
Deletion:
This is significantly harder than insertion.
Standard BST deletion (finding successor/predecessor).
Handle the "Double Black" concept if a Black node is removed.
Fix violations based on sibling color and sibling's children colors.
Language Choice: Python is generally more accessible for algorithmic demonstration due to readability, though C++ is common for systems programming. I will use Python for clarity.
Structure of the response:
Conceptual Overview: Briefly explain what a Red-Black Tree is and why it's useful (self-balancing, O(log n)).
Else (Uncle Black) -> if node is right child -> rotate left(parent), then rotate right(grandpa).
Symmetric for right child.
Root always Black.
Deletion Fix:
This is the tricky part.
Let x be the node that moved into y's original position.
If y (removed node) was Black, we have a black-height violation.
While x is not root and x is Black:
If x is left child:
Sibling w = parent.right.
Case 1: Sibling is Red -> Swap colors, rotate left(parent). Update sibling.
Case 2: Sibling is Black and both children Black -> Sibling becomes Red, move x up.
Case 3: Sibling is Black, left child Red, right child Black -> Swap sibling/child colors, rotate right(sibling).
Case 4: Sibling is Black, right child Red -> Recolor, rotate left(parent), set x to root to exit loop.
Set x color to Black.
Refining the Deletion Logic:
The standard "CLRS" (Introduction to Algorithms) approach uses a transplant helper. I will stick to that standard as it's robust.
Add comments explaining the cases (especially for delete).
Include a printing function (like an inorder traversal or tree pretty-print) so the user can visualize the result.
Let's write the solution. I will focus on a clean, class-based structure.
Self-Correction during drafting: Deletion is complex. I need to be careful with variable names (x, y, z) so they match standard textbooks or are intuitive. z is the node to delete. y is the node actually removed (either z or its successor). x is the child that replaces y.
I will provide a complete, runnable Python script.
A Red-Black Tree is a self-balancing binary search tree. It maintains balance through a set of rules regarding node coloring (Red or Black) and specific rotation operations.
Here is a complete implementation in Python including insertion, deletion, and a helper method to print the tree structure visually.
Python Implementation
python
How it Works
Properties: The tree maintains five specific properties to ensure it remains roughly balanced (guaranteeing O(logn) operations).
Nodes are Red or Black.
Root is Black.
Leaves (NIL) are Black.
Red nodes have Black children.
Every path from a node to its descendant leaves has the same number of Black nodes.
Insertion:
Insert like a standard Binary Search Tree (BST).
Color the new node RED.
Use fix_insert to re-balance. If the parent is Red, we have a "Double Red" violation. We fix this based on the color of the Uncle (parent's sibling):
Uncle is Red: Simple recoloring.
Uncle is Black: Requires rotation (Left or Right) and recoloring.
Deletion:
Perform standard BST delete.
If a Red node is removed, properties are preserved.
If a Black node is removed, we create a "Double Black" situation (conceptually). The fix_delete method resolves this by looking at the Sibling of the deleted node.
It involves 4 Cases based on Sibling's color and the color of Sibling's children, handled via rotations and recoloring.
import sys
# Node class definition
class Node:
def __init__(self, key, color="RED"):
self.key = key
self.left = None
self.right = None
self.parent = None
self.color = color # New nodes are typically RED
class RedBlackTree:
def __init__(self):
# Sentinel node (NIL) represents all leaves and the parent of the root
self.NIL = Node(None, color="BLACK")
self.root = self.NIL
# --- Basic Rotations ---
def left_rotate(self, x):
y = x.right
x.right = y.left
if y.left != self.NIL:
y.left.parent = x
y.parent = x.parent
if x.parent == self.NIL:
self.root = y
elif x == x.parent.left:
x.parent.left = y
else:
x.parent.right = y
y.left = x
x.parent = y
def right_rotate(self, x):
y = x.left
x.left = y.right
if y.right != self.NIL:
y.right.parent = x
y.parent = x.parent
if x.parent == self.NIL:
self.root = y
elif x == x.parent.right:
x.parent.right = y
else:
x.parent.left = y
y.right = x
x.parent = y
# --- Insertion ---
def insert(self, key):
node = Node(key)
node.left = self.NIL
node.right = self.NIL
node.parent = self.NIL
y = self.NIL
x = self.root
# Find insertion position
while x != self.NIL:
y = x
if node.key < x.key:
x = x.left
else:
x = x.right
node.parent = y
if y == self.NIL:
self.root = node
elif node.key < y.key:
y.left = node
else:
y.right = node
# Fix the tree
self.fix_insert(node)
def fix_insert(self, k):
while k.parent.color == "RED":
if k.parent == k.parent.parent.right:
u = k.parent.parent.left # Uncle
if u.color == "RED":
# Case 1: Uncle is Red -> Recolor
u.color = "BLACK"
k.parent.color = "BLACK"
k.parent.parent.color = "RED"
k = k.parent.parent
else:
# Case 2: Uncle is Black (Triangle shape) -> Rotate Parent
if k == k.parent.left:
k = k.parent
self.right_rotate(k)
# Case 3: Uncle is Black (Line shape) -> Rotate Grandparent & Recolor
k.parent.color = "BLACK"
k.parent.parent.color = "RED"
self.left_rotate(k.parent.parent)
else:
# Mirror cases for left parent
u = k.parent.parent.right # Uncle
if u.color == "RED":
# Case 1 Mirror
u.color = "BLACK"
k.parent.color = "BLACK"
k.parent.parent.color = "RED"
k = k.parent.parent
else:
# Case 2 Mirror
if k == k.parent.right:
k = k.parent
self.left_rotate(k)
# Case 3 Mirror
k.parent.color = "BLACK"
k.parent.parent.color = "RED"
self.right_rotate(k.parent.parent)
if k == self.root:
break
self.root.color = "BLACK"
# --- Deletion ---
def delete(self, key):
self._delete_node_helper(self.root, key)
def _delete_node_helper(self, node, key):
# Find the node to delete
z = self.NIL
while node != self.NIL:
if node.key == key:
z = node
break
if node.key <= key:
node = node.right
else:
node = node.left
if z == self.NIL:
print(f"Key {key} not found in the tree.")
return
y = z
y_original_color = y.color
x = None
if z.left == self.NIL:
x = z.right
self._transplant(z, z.right)
elif z.right == self.NIL:
x = z.left
self._transplant(z, z.left)
else:
# Node has two children, find successor
y = self._minimum(z.right)
y_original_color = y.color
x = y.right
if y.parent == z:
x.parent = y
else:
self._transplant(y, y.right)
y.right = z.right
y.right.parent = y
self._transplant(z, y)
y.left = z.left
y.left.parent = y
y.color = z.color
if y_original_color == "BLACK":
self._fix_delete(x)
def _transplant(self, u, v):
# Replaces subtree rooted at u with subtree rooted at v
if u.parent == self.NIL:
self.root = v
elif u == u.parent.left:
u.parent.left = v
else:
u.parent.right = v
v.parent = u.parent
def _fix_delete(self, x):
while x != self.root and x.color == "BLACK":
if x == x.parent.left:
s = x.parent.right # Sibling
# Case 1: Sibling is RED
if s.color == "RED":
s.color = "BLACK"
x.parent.color = "RED"
self.left_rotate(x.parent)
s = x.parent.right
# Case 2: Sibling is BLACK and both children are BLACK
if s.left.color == "BLACK" and s.right.color == "BLACK":
s.color = "RED"
x = x.parent
else:
# Case 3: Sibling is BLACK, left child RED, right child BLACK
if s.right.color == "BLACK":
s.left.color = "BLACK"
s.color = "RED"
self.right_rotate(s)
s = x.parent.right
# Case 4: Sibling is BLACK, right child RED
s.color = x.parent.color
x.parent.color = "BLACK"
s.right.color = "BLACK"
self.left_rotate(x.parent)
x = self.root
else:
# Mirror cases for right child
s = x.parent.left
if s.color == "RED":
s.color = "BLACK"
x.parent.color = "RED"
self.right_rotate(x.parent)
s = x.parent.left
if s.right.color == "BLACK" and s.left.color == "BLACK":
s.color = "RED"
x = x.parent
else:
if s.left.color == "BLACK":
s.right.color = "BLACK"
s.color = "RED"
self.left_rotate(s)
s = x.parent.left
s.color = x.parent.color
x.parent.color = "BLACK"
s.left.color = "BLACK"
self.right_rotate(x.parent)
x = self.root
x.color = "BLACK"
def _minimum(self, node):
while node.left != self.NIL:
node = node.left
return node
# --- Utility: Print Tree ---
def print_tree(self):
if self.root == self.NIL:
print("Tree is empty.")
return
self._print_helper(self.root, "", True)
def _print_helper(self, node, indent, last):
if node != self.NIL:
sys.stdout.write(indent)
if last:
sys.stdout.write("R----")
indent += " "
else:
sys.stdout.write("L----")
indent += "| "
color_str = "RED" if node.color == "RED" else "BLACK"
print(f"{node.key}({color_str})")
self._print_helper(node.left, indent, False)
self._print_helper(node.right, indent, True)
# --- Usage Example ---
if __name__ == "__main__":
bst = RedBlackTree()
print("Inserting: 10, 20, 30, 15, 25, 5")
bst.insert(10)
bst.insert(20)
bst.insert(30)
bst.insert(15)
bst.insert(25)
bst.insert(5)
print("\nTree Structure:")
bst.print_tree()
print("\nDeleting 20...")
bst.delete(20)
bst.print_tree()
print("\nDeleting 10...")
bst.delete(10)
bst.print_tree()