使用python实现一个表达红黑树的demo
时间: 2023-07-25 18:18:14 浏览: 137
红黑树demo python代码
下面是一个用 Python 实现红黑树的简单示例代码:
```python
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.color = 1
class RedBlackTree:
def __init__(self):
self.nil = Node(0)
self.nil.color = 0
self.root = self.nil
def rotate_left(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 rotate_right(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
def insert(self, key):
node = Node(key)
node.parent = None
node.val = key
node.left = self.nil
node.right = self.nil
node.color = 1
y = None
x = self.root
while x != self.nil:
y = x
if node.val < x.val:
x = x.left
else:
x = x.right
node.parent = y
if y == None:
self.root = node
elif node.val < y.val:
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, k):
while k.parent.color == 1:
if k.parent == k.parent.parent.right:
u = k.parent.parent.left
if u.color == 1:
u.color = 0
k.parent.color = 0
k.parent.parent.color = 1
k = k.parent.parent
else:
if k == k.parent.left:
k = k.parent
self.rotate_right(k)
k.parent.color = 0
k.parent.parent.color = 1
self.rotate_left(k.parent.parent)
else:
u = k.parent.parent.right
if u.color == 1:
u.color = 0
k.parent.color = 0
k.parent.parent.color = 1
k = k.parent.parent
else:
if k == k.parent.right:
k = k.parent
self.rotate_left(k)
k.parent.color = 0
k.parent.parent.color = 1
self.rotate_right(k.parent.parent)
if k == self.root:
break
self.root.color = 0
def inorder(self, node):
if node == self.nil:
return
self.inorder(node.left)
print(node.val, end=' ')
self.inorder(node.right)
tree = RedBlackTree()
tree.insert(7)
tree.insert(3)
tree.insert(18)
tree.insert(10)
tree.insert(22)
tree.insert(8)
tree.insert(11)
tree.insert(26)
tree.inorder(tree.root)
```
该示例代码实现了红黑树的插入和中序遍历。其中,节点颜色用 1 表示红色,0 表示黑色,nil 表示空节点(即叶节点)。在插入节点时,通过 fix_insert 方法修正红黑树的性质,使其满足以下特征:
1. 每个节点要么是黑色,要么是红色。
2. 根节点是黑色。
3. 每个叶节点(nil)是黑色。
4. 如果一个节点是红色的,则其子节点必须是黑色的。
5. 从一个节点到该节点的子孙节点的所有路径上包含相同数目的黑色节点。
阅读全文