Contemplating the Implementation
\n\n
I'm focused on the fundamental properties of Red-Black Trees. Right now, I'm solidifying my understanding of the color-coding rules and the need for self-balancing. Insertion and deletion are the main goals; both require careful consideration of these properties to maintain the tree's balance. I'm visualizing the rotations and recoloring operations.
Delving into Node Structure
\n\n
My current focus is on the Node class. I'm considering the best way to represent the color attribute – using an enum seems like a clean approach. I'm also thinking about the role of the parent attribute and whether it simplifies or complicates the code. Further, I'm evaluating the implications of a sentinel NIL node to streamline operations like insertion and deletion. This approach seems promising for managing edge cases.
Planning Deletion Strategies
\n\n
My current hurdle is the deletion implementation. I'm focusing on the transplant helper function, a pivotal component. I'm also grappling with the cases that arise when deleting a node – particularly the complexities of handling double-black situations. I'm carefully analyzing the different deletion scenarios to ensure the tree maintains its balance after the operation. I am working to define those double-black fixup cases.
Considering Fix-Up Scenarios
\n\n
My current focus is the intricacy of the deletion fixup process. I'm deep diving into the sibling cases and the required rotations and recolorings, specifically when the sibling is black. I'm also ensuring the edge cases are accounted for as I go, particularly when dealing with the root. I'm focusing on creating robust tests for all cases.
Structuring the Codebase
\n\n
My current thinking revolves around the overall organization of the code. I'm focusing on defining the RedBlackTree class and its core methods. The goal is a clear, concise design where each method encapsulates a specific task. I plan on including helper methods, like transplant, to keep the main functions, insert and delete, more readable. I'm focusing on efficiency and readability.
Considering Root and Balance
\n\n
My current thinking centers on the root node and balancing operations. Specifically, I'm verifying the edge case handling for rotations that involve the root. I'm also ensuring the color properties are maintained after each insert and delete operation. I'm refining the logic to ensure that the black height remains consistent throughout the tree.
Refining Insertion Logic
\n\n
My current thinking is focused on the insert fixup and its interaction with rotations. Specifically, I'm verifying the edge cases for inserting nodes in different positions and how those impact the root's color and the tree's balance. I am using a visual tool to see how colors change after rotations. I'm focusing on test cases to validate different insertion scenarios.
Implementing a Red-Black Tree (RBT) is a classic computer science problem. It requires strict adherence to properties to maintain balance (O(logn) search/insert/delete).
Below is a complete Python implementation. It uses a Sentinel Node (TNULL). Using a sentinel instead of None significantly simplifies the code by treating leaf nodes as actual objects with a color (Black), avoiding null-pointer exceptions during rotations.
Key Properties Implemented
- Nodes are Red or Black.
- Root is always Black.
- Leaves (
TNULL) are Black.
- If a node is Red, children must be Black.
- Every path from a node to its descendant leaves has the same number of Black nodes.
The Python Code
# Constants for readability
RED = 1
BLACK = 0
class Node:
def __init__(self, item):
self.item = item
self.parent = None
self.left = None
self.right = None
self.color = RED # New nodes are always inserted as RED
class RedBlackTree:
def __init__(self):
# Sentinel node representing NIL (leaves)
self.TNULL = Node(0)
self.TNULL.color = BLACK
self.TNULL.left = None
self.TNULL.right = None
self.root = self.TNULL
# ==========================================
# HELPER FUNCTIONS
# ==========================================
def _minimum(self, node):
while node.left != self.TNULL:
node = node.left
return node
def _replace_parent_ref(self, u, v):
"""Transplant: Replaces subtree rooted at u with subtree rooted at v"""
if u.parent is None:
self.root = v
elif u == u.parent.left:
u.parent.left = v
else:
u.parent.right = v
v.parent = u.parent
# ==========================================
# ROTATIONS
# ==========================================
def left_rotate(self, x):
y = x.right
x.right = y.left
if y.left != self.TNULL:
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 right_rotate(self, x):
y = x.left
x.left = y.right
if y.right != self.TNULL:
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
# ==========================================
# INSERTION
# ==========================================
def insert(self, key):
node = Node(key)
node.parent = None
node.item = key
node.left = self.TNULL
node.right = self.TNULL
node.color = RED # Always insert as Red
y = None
x = self.root
# Standard BST Insert
while x != self.TNULL:
y = x
if node.item < x.item:
x = x.left
else:
x = x.right
node.parent = y
if y is None:
self.root = node
elif node.item < y.item:
y.left = node
else:
y.right = node
if node.parent is None:
node.color = BLACK
return
if node.parent.parent is None:
return
self._insert_fixup(node)
def _insert_fixup(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:
if k == k.parent.left:
# Case 2: Uncle is Black, Triangle shape (Rotate parent)
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 image of above
u = k.parent.parent.right
if u.color == RED:
u.color = BLACK
k.parent.color = BLACK
k.parent.parent.color = RED
k = k.parent.parent
else:
if k == k.parent.right:
k = k.parent
self.left_rotate(k)
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, data):
z = self.root
# Find node
while z != self.TNULL:
if z.item == data:
break
if data < z.item:
z = z.left
else:
z = z.right
if z == self.TNULL:
print("Cannot find key in the tree")
return
y = z
y_original_color = y.color
if z.left == self.TNULL:
x = z.right
self._replace_parent_ref(z, z.right)
elif z.right == self.TNULL:
x = z.left
self._replace_parent_ref(z, z.left)
else:
# Node has two children
y = self._minimum(z.right)
y_original_color = y.color
x = y.right
if y.parent == z:
x.parent = y
else:
self._replace_parent_ref(y, y.right)
y.right = z.right
y.right.parent = y
self._replace_parent_ref(z, y)
y.left = z.left
y.left.parent = y
y.color = z.color
if y_original_color == BLACK:
self._delete_fixup(x)
def _delete_fixup(self, x):
while x != self.root and x.color == BLACK:
if x == x.parent.left:
s = x.parent.right # Sibling
if s.color == RED:
# Case 1: Sibling is Red
s.color = BLACK
x.parent.color = RED
self.left_rotate(x.parent)
s = x.parent.right
if s.left.color == BLACK and s.right.color == BLACK:
# Case 2: Sibling's children are both Black
s.color = RED
x = x.parent
else:
if s.right.color == BLACK:
# Case 3: Sibling's inner child is Red
s.left.color = BLACK
s.color = RED
self.right_rotate(s)
s = x.parent.right
# Case 4: Sibling's outer child is Red
s.color = x.parent.color
x.parent.color = BLACK
s.right.color = BLACK
self.left_rotate(x.parent)
x = self.root
else:
# Mirror image
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
# ==========================================
# PRINTING / UTILS
# ==========================================
def print_tree(self):
self._print_helper(self.root, "", True)
def _print_helper(self, curr, indent, last):
if curr != self.TNULL:
print(indent, end="")
if last:
print("R----", end="")
indent += " "
else:
print("L----", end="")
indent += "| "
s_color = "RED" if curr.color == RED else "BLACK"
print(str(curr.item) + "(" + s_color + ")")
self._print_helper(curr.left, indent, False)
self._print_helper(curr.right, indent, True)
# ==========================================
# USAGE EXAMPLE
# ==========================================
if __name__ == "__main__":
bst = RedBlackTree()
print("--- Insertion Phase ---")
elements = [55, 40, 65, 60, 75, 57]
for el in elements:
print(f"Inserting {el}...")
bst.insert(el)
bst.print_tree()
print("\n--- Deletion Phase ---")
print("Deleting 40 (Leaf with Red Children logic)...")
bst.delete(40)
bst.print_tree()
print("\nDeleting 65 (Node with two children)...")
bst.delete(65)
bst.print_tree()
How the Operations Work
1. Insertion
Every new node is initially Red. This might violate the rule "No two Reds in a row". We fix this by looking at the Uncle (Parent's sibling).
- Case 1 (Uncle is Red): We have too much "Redness". We recolor the Parent/Uncle to Black and the Grandparent to Red. We then check the Grandparent for violations.
- Case 2 (Uncle is Black, Triangle shape): We rotate the parent to turn the "Triangle" relationship (Parent-Child) into a "Line" relationship. This converts it to Case 3.
- Case 3 (Uncle is Black, Line shape): We rotate the Grandparent and swap colors (Parent becomes Black, Grandparent becomes Red).
2. Deletion
This is more complex. We first do a standard BST delete. If the node actually removed (or the node that moved up to replace it) was Black, we have violated the "Black Height" property. We fix this by looking at the Sibling:
- Case 1 (Sibling is Red): Rotate to make the sibling Black.
- Case 2 (Sibling is Black, both its children are Black): We can rob a Black from the sibling (make it Red) and push the problem up to the parent.
- Case 3 (Sibling is Black, near child Red): Rotate sibling to push the Red node to the "outer" side (Case 4).
- Case 4 (Sibling is Black, far child Red): Rotate the parent and recolor. This fills the Black height gap completely.