本文整理汇总了Python中TreeNode.TreeNode.setkeyvalue方法的典型用法代码示例。如果您正苦于以下问题:Python TreeNode.setkeyvalue方法的具体用法?Python TreeNode.setkeyvalue怎么用?Python TreeNode.setkeyvalue使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类TreeNode.TreeNode
的用法示例。
在下文中一共展示了TreeNode.setkeyvalue方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: BST
# 需要导入模块: from TreeNode import TreeNode [as 别名]
# 或者: from TreeNode.TreeNode import setkeyvalue [as 别名]
class BST(object):
def __init__(self, key, value):
self.root = TreeNode(key, value)
self.size = 1
def insert(self, key, value):
if self.size == 0:
self.root.setkeyvalue(key, value)
self.size += 1
return
newnode = TreeNode(key, value)
now = self.root
while now:
if newnode.getkey() < now.getkey():
if now.getleft() == None:
now.setleft(newnode)
newnode.setparent(now)
self.size += 1
break;
else:
now = now.getleft()
elif newnode.getkey() > now.getkey():
if now.getright() == None:
now.setright(newnode)
newnode.setparent(now)
self.size += 1
break
else:
now = now.getright()
else:
now.setkeyvalue(key, newnode.getvalue())
break
def delete(self, key):
if self.size == 0:
raise RuntimeError("The tree is already empty")
node = self.find(key)
delkey, delval = node.getkey(), node.getvalue()
if node.getleft() == None and node.getright() == None:
self.deleteleaf(node)
return delkey, delval
elif node.getleft() == None or node.getright() == None:
self.deleteWithOne(node)
return delkey, delval
else:
rep = self.findrep(node)
node.setkeyvalue(rep.getkey(), rep.getvalue())
if rep.getleft() == None and rep.getright() == None:
self.deleteleaf(rep)
return delkey, delval
else:
self.deleteWithOne(rep)
return delkey, delval
def deleteleaf(self, node):
if node.isroot():
self.__init__(None, None)
self.size -= 1
elif node.isleft():
node.getparent().setleft(None)
self.size -= 1
else:
if node.isright():
node.getparent().setright(None)
self.size -= 1
def deleteWithOne(self, node):
if node.getleft() == None:
if node.isroot():
self.root = node.getright()
self.root.setparent(None)
self.size -= 1
else:
node.getparent().setright(node.getright())
node.getright().setparent(node.getparent())
self.size -= 1
else:
if node.isroot():
self.root = node.getleft()
self.root.setparent(None)
self.size -= 1
else:
node.getparent().setleft(node.getleft())
node.getleft().setparent(node.getparent())
self.size -= 1
def findrep(self, node):
now = node.getright()
while now.getleft():
now = now.getleft()
return now
def getsize(self):
return self.size
#.........这里部分代码省略.........