红黑树的python代码实现
时间: 2023-06-04 10:08:48 浏览: 119
以下是红黑树 Python 代码实现示例:
```python
class Node:
def __init__(self, key):
self.key = key
self.parent = None
self.left_child = None
self.right_child = None
self.color = 1 # red = 1, black = 0
class RedBlackTree:
def __init__(self):
self.nil = Node(None)
self.nil.color = 0 # set nil to black node
self.root = self.nil
def left_rotate(self, x):
y = x.right_child
x.right_child = y.left_child
if y.left_child != self.nil:
y.left_child.parent = x
y.parent = x.parent
if x.parent == self.nil:
self.root = y
elif x == x.parent.left_child:
x.parent.left_child = y
else:
x.parent.right_child = y
y.left_child = x
x.parent = y
def right_rotate(self, x):
y = x.left_child
x.left_child = y.right_child
if y.right_child != self.nil:
y.right_child.parent = x
y.parent = x.parent
if x.parent == self.nil:
self.root = y
elif x == x.parent.right_child:
x.parent.right_child = y
else:
x.parent.left_child = y
y.right_child = x
x.parent = y
def insert(self, key):
z = Node(key)
z.parent = self.nil
z.left_child = self.nil
z.right_child = self.nil
z.color = 1
y = self.nil
x = self.root
while x != self.nil:
y = x
if z.key < x.key:
x = x.left_child
else:
x = x.right_child
z.parent = y
if y == self.nil:
self.root = z
elif z.key < y.key:
y.left_child = z
else:
y.right_child = z
self.insert_fixup(z)
def insert_fixup(self, z):
while z.parent.color == 1:
if z.parent == z.parent.parent.left_child:
y = z.parent.parent.right_child
if y.color == 1:
z.parent.color = 0
y.color = 0
z.parent.parent.color = 1
z = z.parent.parent
else:
if z == z.parent.right_child:
z = z.parent
self.left_rotate(z)
z.parent.color = 0
z.parent.parent.color = 1
self.right_rotate(z.parent.parent)
else:
y = z.parent.parent.left_child
if y.color == 1:
z.parent.color = 0
y.color = 0
z.parent.parent.color = 1
z = z.parent.parent
else:
if z == z.parent.left_child:
z = z.parent
self.right_rotate(z)
z.parent.color = 0
z.parent.parent.color = 1
self.left_rotate(z.parent.parent)
self.root.color = 0
def search(self, key):
current = self.root
while current != self.nil and key != current.key:
if key < current.key:
current = current.left_child
else:
current = current.right_child
if current == self.nil:
return None
else:
return current.key
def inorder_traversal(self, node):
if node == self.nil:
return
self.inorder_traversal(node.left_child)
print(node.key, end=" ")
self.inorder_traversal(node.right_child)
```
请注意,这只是一种红黑树的实现方法示例,可能并不完全符合所有情况。它具有插入,搜索和中序(左,根,右)遍历功能。
阅读全文