用python学有个红黑树
时间: 2024-04-04 17:27:50 浏览: 119
红黑树demo python代码
红黑树是一种自平衡的二叉搜索树,它在插入和删除节点时通过一系列的旋转和重新着色操作来保持树的平衡。Python是一种功能强大且易于学习的编程语言,可以用来实现红黑树。
在Python中,你可以使用类来定义一个红黑树的节点,并在节点类中实现插入、删除和搜索等操作。下面是一个简单的红黑树的实现示例:
```python
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.parent = None
self.color = 1 # 1表示红色,0表示黑色
class RedBlackTree:
def __init__(self):
self.nil = Node(None) # 哨兵节点,表示空节点
self.root = self.nil
def insert(self, key):
node = Node(key)
node.left = self.nil
node.right = self.nil
node.color = 1 # 新插入的节点为红色
parent = None
current = self.root
while current != self.nil:
parent = current
if node.key < current.key:
current = current.left
else:
current = current.right
node.parent = parent
if parent is None:
self.root = node
elif node.key < parent.key:
parent.left = node
else:
parent.right = node
self._insert_fixup(node)
def _insert_fixup(self, node):
while node.parent.color == 1:
if node.parent == node.parent.parent.left:
uncle = node.parent.parent.right
if uncle.color == 1:
node.parent.color = 0
uncle.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)
else:
uncle = node.parent.parent.left
if uncle.color == 1:
node.parent.color = 0
uncle.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)
self.root.color = 0
def _left_rotate(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 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.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 search(self, key):
current = self.root
while current != self.nil and key != current.key:
if key < current.key:
current = current.left
else:
current = current.right
return current
def delete(self, key):
node = self.search(key)
if node == self.nil:
return
self._delete_node(node)
def _delete_node(self, node):
# 省略删除节点的代码
# 其他辅助方法省略...
```
这只是一个简单的红黑树实现示例,你可以根据需要进行扩展和优化。希望对你学习红黑树有所帮助!
阅读全文