原理讲解参考:https://www.cnblogs.com/skywang12345/p/3245399.html
'''
1) 每个节点是黑色或者红色。
2) 根节点是黑色。
3) 每个叶子节点(nil)是黑色。
4) 红色节点的子节点必须是黑色。
5) 从一个节点到该节点的子孙节点的所有路径上包含相同数目的黑节点。
'''
import random
class Color:
Red = 1
Black = 2
class NullNode:
def __init__(self):
self.color = Color.Black
self.parent = None
self.left = None
self.right = None
class RbTreeNode:
def __init__(self, key, color):
self.key = key
self.color = color
self.parent = NullNode()
self.left = NullNode()
self.right = NullNode()
def format(self):
if self.color == Color.Red:
return "\033[31m%s\033[0m" % self.key
else:
return "\033[34m%s\033[0m" % self.key
def left_rotate(t, x):
p = x.parent
r = x.right
if isinstance(r, NullNode):
raise Exception("can not left_rotate while right child is Null ")
# 右节点设为父节点
r.parent = p
if x == p.left:
p.left = r
else:
p.right = r
# 右左节点设置x的右节点
r.left.parent = x
x.right = r.left
# x设为左节点
r.left = x
x.parent = r
if not r.parent or isinstance(r.parent, NullNode):
t = r
return t
def right_rotate(t, x):
p = x.parent
l = x.left
if isinstance(l, NullNode):
raise Exception("can not right_rotate while right child is Null ")
l.parent = p
if x == p.left:
p.left = l
else:
p.right = l
l.right.parent = x
x.left = l.right
l.right = x
x.parent = l
if not l.parent or isinstance(l.parent, NullNode):
t