The user wants a program that implements a Red-Black tree.
1. Understand the Requirements:
- Data Structure: Red-Black Tree (Self-Balancing Binary Search Tree).
- Core Operations: Insertion, Deletion (optional but good for completeness), Search, Traversal (for verification).
- Language: Not specified. Python or C++ are standard choices. Python is generally more readable for algorithms, while C++ is better for low-level pointer manipulation. I'll choose Python for its accessibility, but structure it clearly so it can be translated. Self-correction: Actually, C++ is often preferred for data structure examples to show memory management, but Python is great for logic. Let's stick to Python for clarity, maybe add a note about C++. Let's provide a Python implementation.
- Key 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.
2. Structure the Program:
- Class
Node: Needs color, key, left, right, parent.
- Class
RedBlackTree:
__init__: Initialize the NIL sentinel node and the root.
insert(key): Public wrapper.
_insert_fixup(node): The logic to balance the tree after standard BST insertion.
delete(key): (This is complex. I should decide whether to include it. The prompt asks for an implementation. A minimal viable implementation usually implies Insert and Search. Delete is notoriously long. I will implement Insertion fully as it demonstrates the rotation and recoloring logic best. I will add a note about Deletion complexity but maybe omit the full code to keep it concise, or include a placeholder. Decision: I'll implement Insertion and Search. I will not implement Deletion unless specifically asked, because it bloats the code significantly and often confuses the learner, whereas Insertion teaches the core concepts (rotations, recoloring).
search(key): Standard BST search.
_rotate_left(node): Helper.
_rotate_right(node): Helper.
print_tree(): Visualizer helper.
3. Drafting the Logic (Mental or Scratchpad):
-
Sentinel (NIL or TNULL):
- Crucial for R-B trees to handle leaves cleanly.
- Color: Black.
- Value: Irrelevant.
-
Left Rotation:
y = x.right
x.right = y.left
- if
y.left != NIL: y.left.parent = x
y.parent = x.parent
- if
x.parent == NIL: root = y
- else if
x == x.parent.left: x.parent.left = y
- else:
x.parent.right = y
y.left = x
x.parent = y
-
Insertion:
- Standard BST insert.
- New node
z starts as Red.
z.left = NIL, z.right = NIL.
- Fix-up loop:
while z.parent.color == RED:
- Case A: Parent is left child of Grandparent.
- Uncle
y is Grandparent's right child.
- Case 1: Uncle is Red -> Recolor Parent, Uncle, Grandparent. Move
z to Grandparent.
- Case 2: Uncle is Black (or NIL).
- If
z is right child: Left rotate Parent. z becomes old parent.
- Recolor Parent and Grandparent. Right rotate Grandparent.
- Case B: Parent is right child (Symmetric).
- Finally:
root.color = BLACK.
4. Refining the Code (Python):
-
Imports: sys (for max size if needed, or just logic). enum is nice for colors but constants 0/1 or strings "RED"/"BLACK" are easier. Let's use strings for readability.
-
Class Node:
class Node:
def __init__(self, val, color="RED"):
self.val = val
self.parent = None
self.left = None
self.right = None
self.color = color
-
Class RBTree:
Need to handle the NIL node carefully.
class RedBlackTree:
def __init__(self):
self.NIL = Node(0, "BLACK") # Sentinel
self.root = self.NIL
5. Writing the Code (Iterative refinement):
-
Insertion:
- Find spot (standard BST).
- Link parent.
- Link children to NIL.
- Color RED.
- Call
fix_insert.
-
Fix Insertion:
- Need to handle the 3 cases.
- Careful with
z.parent.parent access (check if root).
-
Rotations:
- Must update
parent pointers. This is the most error-prone part.
- Must handle root updates.
-
Printing:
- A simple inorder traversal or a level-order print to show the tree structure. In-order is easier to verify (should be sorted).
6. Adding Deletion (Reconsideration):
While complex, a "Red-Black Tree implementation" is often expected to have deletion. However, the code length doubles. For a generated response, a clean, working Insert/Search implementation is usually preferred over a buggy or cluttered full implementation. I will provide the Insertion, Search, and Rotation logic, as this covers 80% of the "learning" requirement. I'll add a comment about deletion.
7. Final Code Structure:
- Define Color constants.
- Node class.
- RBTree class.
rotate_left, rotate_right.
insert, fix_insert.
search.
inorder_print (helper).
- Main block to demonstrate usage.
8. Self-Correction/Refinement during coding:
- Issue: Python references. When assigning
node = self.NIL, ensure self.NIL is unique.
- Issue: The
fix_insert loop. Remember to set z = z.parent.parent correctly in Case 1.
- Issue: Symmetry in Case 2/3 (triangles vs lines).
9. Final Polish:
Add comments explaining the 5 properties and what specific lines of code do (e.g., "Case 1: Uncle is Red"). This adds value.
Let's write the Python code.
-
Setup:
class Node:
...
class RedBlackTree:
...
-
Rotations:
Standard algorithm. Keep track of x, y, and x.parent.
-
Insert Fix:
while k.parent.color == 1: # 1 is RED
if k.parent == k.parent.parent.right:
# ... logic ...
else:
# ... logic ...
-
Output:
The output needs to show that it balances. Printing color + value is essential.
Let's produce the solution. I will choose Python for its readability. I will implement Insertion, Search, and Traversal. I will omit Deletion to keep the code concise and readable, as Deletion in RB trees is significantly more complex and often obscures the basic mechanics for a first-time implementer, but I will mention it. Correction: Actually, a robust implementation usually asks for deletion. But usually, when people ask for "A program that implements...", they are looking for the structural definition and insertion logic. I'll stick to Insert/Search/Traverse.
(Self-Correction): Make sure the sentinel NIL is handled correctly. self.NIL.left and self.NIL.right shouldn't be accessed, but self.NIL itself acts as the child.
Final check on Python syntax:
class Node:
__init__
self.root = self.NIL
Looks good. Proceed to generate.
Here is a complete implementation of a Red-Black Tree in Python.
This implementation includes the core properties of a Red-Black Tree:
- Every node is either Red or Black.
- The root is Black.
- All leaves (NIL nodes) are Black.
- If a node is Red, both its children are Black.
- Every path from a node to its descendant leaves contains the same number of Black nodes.
It supports Insertion, Search, and In-order Traversal. (Deletion is omitted as it is significantly more complex, but insertion is sufficient to demonstrate the balancing mechanics).
Python Implementation
class Color:
RED = 0
BLACK = 1
class Node:
def __init__(self, value, color=Color.RED, parent=None):
self.value = value
self.color = color
self.parent = parent
self.left = None
self.right = None
class RedBlackTree:
def __init__(self):
# The NIL node acts as the sentinel leaf for all None pointers
self.NIL = Node(value=None, color=Color.BLACK)
self.root = self.NIL
# --- Public Methods ---
def insert(self, value):
"""Inserts a value into the tree and fixes properties."""
new_node = Node(value, color=Color.RED, parent=None)
new_node.left = self.NIL
new_node.right = self.NIL
y = None # Parent pointer for the new node
x = self.root
# 1. Standard BST insertion logic to find the correct spot
while x != self.NIL:
y = x
if new_node.value < x.value:
x = x.left
else:
x = x.right
new_node.parent = y
if y is None: # Tree was empty
self.root = new_node
elif new_node.value < y.value:
y.left = new_node
else:
y.right = new_node
# 2. Fix the Red-Black properties
self._fix_insert(new_node)
def search(self, value):
"""Returns the node if found, else None."""
node = self.root
while node != self.NIL:
if value == node.value:
return node
elif value < node.value:
node = node.left
else:
node = node.right
return None
def print_tree(self):
"""Prints the tree in sorted order with colors."""
if self.root == self.NIL:
print("Tree is empty")
else:
self._print_helper(self.root, "", True)
# --- Private Helper Methods ---
def _rotate_left(self, x):
"""Rotate node x to the left."""
y = x.right
x.right = y.left
if y.left != self.NIL:
y.left.parent = x
y.parent = x.parent
if x.parent is None:
self.root = y
elif x == x.parent.left:
x.parent.left = y
else:
x.parent.right = y
y.left = x
x.parent = y
def _rotate_right(self, x):
"""Rotate node x to the right."""
y = x.left
x.left = y.right
if y.right != self.NIL:
y.right.parent = x
y.parent = x.parent
if x.parent is None:
self.root = y
elif x == x.parent.right:
x.parent.right = y
else:
x.parent.left = y
y.right = x
x.parent = y
def _fix_insert(self, k):
"""
Fixes the tree after insertion to maintain Red-Black properties.
'k' is the newly inserted node (which is RED).
"""
while k.parent and k.parent.color == Color.RED:
if k.parent == k.parent.parent.right:
# Parent is the right child of Grandparent
u = k.parent.parent.left # Uncle
# Case 1: Uncle is RED -> Recolor
if u.color == Color.RED:
u.color = Color.BLACK
k.parent.color = Color.BLACK
k.parent.parent.color = Color.RED
k = k.parent.parent
else:
# Case 2: Uncle is BLACK and Node is Left Child -> Rotate
if k == k.parent.left:
k = k.parent
self._rotate_right(k)
# Case 3: Uncle is BLACK and Node is Right Child -> Recolor & Rotate
k.parent.color = Color.BLACK
k.parent.parent.color = Color.RED
self._rotate_left(k.parent.parent)
else:
# Parent is the left child of Grandparent (Symmetric to above)
u = k.parent.parent.right # Uncle
if u.color == Color.RED:
# Case 1: Uncle is RED -> Recolor
u.color = Color.BLACK
k.parent.color = Color.BLACK
k.parent.parent.color = Color.RED
k = k.parent.parent
else:
# Case 2: Uncle is BLACK and Node is Right Child -> Rotate
if k == k.parent.right:
k = k.parent
self._rotate_left(k)
# Case 3: Uncle is BLACK and Node is Left Child -> Recolor & Rotate
k.parent.color = Color.BLACK
k.parent.parent.color = Color.RED
self._rotate_right(k.parent.parent)
if k == self.root:
break
self.root.color = Color.BLACK
def _print_helper(self, node, indent, last):
"""Recursive helper to print the tree structure."""
if node != self.NIL:
print(indent, end="")
if last:
print("R----", end="")
indent += " "
else:
print("L----", end="")
indent += "| "
s_color = "RED" if node.color == Color.RED else "BLACK"
print(f"{node.value}({s_color})")
self._print_helper(node.left, indent, False)
self._print_helper(node.right, indent, True)
# --- Usage Example ---
if __name__ == "__main__":
bst = RedBlackTree()
print("Inserting nodes: 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:")
print("(L = Left Child, R = Right Child)")
bst.print_tree()
print("\nSearch for 15:")
result = bst.search(15)
print(f"Found: {result.value}" if result else "Not Found")
print("\nSearch for 99:")
result = bst.search(99)
print(f"Found: {result.value}" if result else "Not Found")
How it Works
- The NIL Sentinel: Standard BSTs use
None for leaf pointers. Red-Black trees treat these leaves as actual "Black" nodes. We create a single NIL object to serve as the terminating node for every branch.
- Insertion:
- The new node starts as RED (to avoid violating the black-height property immediately).
- We perform a standard BST insert.
- Fixup (
_fix_insert):
- If the parent of the new node is Black, the tree is valid.
- If the parent is Red, we have a "Double Red" violation. We fix this using Recoloring and Rotations based on the color of the Uncle (the parent's sibling):
- Case 1 (Uncle is Red): Simply recolor Parent, Uncle, and Grandparent. Move the pointer up to the Grandparent and repeat.
- Case 2 (Uncle is Black, Triangle shape): Perform a rotation on the Parent to straighten the line.
- Case 3 (Uncle is Black, Line shape): Recolor Parent and Grandparent, then rotate the Grandparent in the opposite direction.
- Output: The
print_tree method displays the hierarchy, verifying that no Red node has a Red child.