【发布时间】:2015-08-06 11:05:32
【问题描述】:
下面的 Python Red Black 树实现需要大约 2 秒来执行测试函数,这没有多大意义,因为在打印出测试的情况下树高为 14。所以..我假设我在代码中做了一些愚蠢的事情。您能否提供一些加快代码速度的提示?
import math
BLACK = 0
RED = 1
class RBTreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.color = RED
def setColor(n, c):
n.color = c
return n
def color(n):
if not n:
return BLACK
return n.color
def isRed(n):
return color(n) == RED
def rotateLeft(h):
x = h.right
h.right = x.left
x.left = h
x.color = h.color
h.color = RED
return x
def rotateRight(h):
x = h.left
h.left = x.right
x.right = h
x.color = h.color
h.color = RED
return x
def flipColor(n):
n.left.color = BLACK
n.right.color = BLACK
n.color = RED
return n
def insert(n, v):
if not n:
return RBTreeNode(v)
if v >= n.val:
n.right = insert(n.right, v)
else:
n.left = insert(n.left, v)
if isRed(n.right) and not isRed(n.left):
n = rotateLeft(n)
if isRed(n.left) and isRed(n.left.left):
n = rotateRight(n)
if isRed(n.left) and isRed(n.right):
n = flipColor(n)
return n
def height(n):
if not n:
return 0
h1 = height(n.left)
h2 = height(n.right)
return 1 + max(h1, h2)
def printNode(n, indent):
if not n:
return
print " " * indent,
(v, c) = n.val
print v, "(BLACK)" if c == 0 else "(RED)"
printNode(n.left, indent + 4)
printNode(n.right, indent + 4)
def test():
c = xrange(0, 32768)
tree = None
for i in c:
tree = insert(tree, i)
print 2 * math.log(len(c)) / math.log(2), height(tree)
# printNode(tree, 0)
if __name__ == "__main__":
test()
【问题讨论】:
-
既然这是工作代码,Code Review 不是询问性能增强的更好地方吗?
-
分析您的代码以找到瓶颈。
-
出于好奇,您是否有理由为您的树创建一个类,然后将其他所有内容都设为函数而不是类方法?
标签: python data-structures red-black-tree