好像我的功能运行得很慢。插入100,000个元素大约需要10秒钟,但实际上需要几分钟。
注意:rit_object是一个私有类,它为每个参数放置类型 来自rit_object import *
class EyecuBST(rit_object):
__slots__ = ('left', 'right', 'parent',
'value', 'height', 'size', 'imbalance')
_types = ('EyecuBST', 'EyecuBST', 'EyecuBST',
int, int, int, int)
def createEyecuBST(el, parent):
""" creates a BST containing just this node, and connected
to the given parent node, which is None if this is the root.
Returns the tree node.
"""
return EyecuBST(None, None, parent, el, 0, 1, 0)
def eyecuToString(tr):
""" takes an EyecuBST tree and generates a string containing
an inorder processing of the nodes of the tree. For each
node, the string contains the following information:
value, height, size, imbalance.
Returns the string
"""
if tr == None:
return ""
else:
thisNodeStr = "Value: " + str(tr.value) + ", Height: " + \
str(tr.height) + ", Size: " + str(tr.size) + ", Imbalance: " + \
str(tr.imbalance) + "\n"
return eyecuToString(tr.left) + thisNodeStr + eyecuToString(tr.right)
def insert(tr, el):
""" function to insert an element into a binary search tree
following the rules of binary search trees.
return: an updated tree
precondition: assumed all elements unique
"""
if tr == None:
#print('inserting node root')
return createEyecuBST(el, None)
tr.height = 1
else:
if tr.value > el: #if node is greater than element
if tr.left == None:
tr.left = createEyecuBST(el, tr) #create new node
#print('inserting node left')
tr.size += 1 # size of tree + 1
return tr # return new tree
else:
insert(tr.left, el)
return tr
if tr.left == None:
if tr.right == None:
tr.height = 1
else:
tr.height = tr.right.height + 1
else:
if tr.right == None:
tr.height = tr.left.height + 1
else:
tr.height = max(tr.left.height, tr.right.height) + 1
else:
if tr.right == None:
tr.right = createEyecuBST(el, tr)
#print('inserting node right')
tr.size += 1
return tr
else:
insert(tr.right, el)
return tr
if tr.right == None:
if tr.left == None:
tr.height = 1
else:
tr.height = tr.left.height + 1
else:
if tr.left == None:
tr.height = tr.right.height + 1
else:
tr.height = max(tr.left.height, tr.right.height) + 1
def treeHeight(tr):
"""
Returns the height of the tree rooted at this node. Returns -1
if input tr is an empty tree (None).
"""
if tr is None:
return -1
else:
return tr.height
def treeSize(tr):
"""
Returns the size of the tree rooted at target node. Returns 0
is input tr is an empty tree (None)
"""
if tr is None:
return 0
else:
return tr.size
def treeImbalance(tr):
"""
Returns the imbalance of the tree rooted at target node. Returns 0
if input tr is an empty tree (None)
"""
#if tr is None:
# return 0
#else:
def findNode(tr, val):
""" finds the target node in the tree. Returns the node reference.
Returns None if the node is not in the tree.
precondtion: val is non-negative integer.
"""
# replace with your findNode function code
return None
有什么建议吗?我正在努力让计算时间加快。在我的插入功能,以及如何跟踪不平衡。
答案 0 :(得分:1)
你可以发布整个代码吗?你的插入函数是否在类中?我觉得你做得太多了。我需要查看更多代码才能帮到您。