红黑树python实现
时间: 2023-11-07 21:58:21 浏览: 91
红黑树是一种自平衡的二叉搜索树,其在实现上相对复杂。下面是一个红黑树的Python实现的示例代码:
```python
# 节点类
class Node:
def __init__(self, key):
self.key = key
self.parent = None
self.left = None
self.right = None
self.color = 1 # 红色为1,黑色为0
# 红黑树类
class RedBlackTree:
def __init__(self):
self.nil = Node(None) # 哨兵节点
self.nil.color = 0
self.root = self.nil
def insert(self, key):
node = Node(key)
node.parent = None
node.left = self.nil
node.right = self.nil
node.color = 1
y = None
x = self.root
while x != self.nil:
y = x
if node.key < x.key:
x = x.left
else:
x = x.right
node.parent = y
if y == None:
self.root = node
elif node.key < y.key:
y.left = node
else:
y.right = node
if node.parent == None:
node.color = 0
return
if node.parent.parent == None:
return
self.fix_insert(node)
def fix_insert(self, node):
while node.parent.color == 1:
if node.parent == node.parent.parent.right:
uncle = node.parent.parent.left
if uncle.color == 1:
uncle.color = 0
node.parent.color = 0
node.parent.parent.color = 1
node = node.parent.parent
else:
if node == node.parent.left:
node = node.parent
self.right_rotate(node)
node.parent.color = 0
node.parent.parent.color = 1
self.left_rotate(node.parent.parent)
else:
uncle = node.parent.parent.right
if uncle.color == 1:
uncle.color = 0
node.parent.color = 0
node.parent.parent.color = 1
node = node.parent.parent
else:
if node == node.parent.right:
node = node.parent
self.left_rotate(node)
node.parent.color = 0
node.parent.parent.color = 1
self.right_rotate(node.parent.parent)
if node == self.root:
break
self.root.color = 0
def left_rotate(self, node):
y = node.right
node.right = y.left
if y.left != self.nil:
y.left.parent = node
y.parent = node.parent
if node.parent == None:
self.root = y
elif node == node.parent.left:
node.parent.left = y
else:
node.parent.right = y
y.left = node
node.parent = y
def right_rotate(self, node):
y = node.left
node.left = y.right
if y.right != self.nil:
y.right.parent = node
y.parent = node.parent
if node.parent == None:
self.root = y
elif node == node.parent.right:
node.parent.right = y
else:
node.parent.left = y
y.right = node
node.parent = y
# 创建红黑树对象
rbt = RedBlackTree()
# 插入节点
rbt.insert(10)
rbt.insert(20)
rbt.insert(30)
rbt.insert(40)
rbt.insert(50)
# 相关问题:
阅读全文