我正在为splay树编写代码,但我对splay树的删除方面有疑问。在互联网上研究之后,我发现了这个:
首先搜索要删除的元素并将其展开到顶部。然后执行以下操作
但是如果根没有合适的孩子会怎么样?所以我删除了root并将左子树的根作为新根?
我还需要照顾其他任何条件吗?
如果有帮助,我已经在下面写了删除代码。
def delete(self,key):
res = self.get(key) #The get() function also does the splaying operation as well
if res:
ls = self.root.leftChild
rs = self.root.rightChild
if ls is not None and rs is not None: #has both the child
ls.parent = None
rs.parent = None
current = ls
while ls.hasRightChild():
current = current.rightChild #find the largest element
self.get(current.key)
rs.parent = current
current.rightChild = rs
self.root = current
elif ls is None and rs is not None: #has no left child
rs.parent = None
self.root = rs
elif ls is None and rs is None: #has no left or right child ie the tree contains only one node
self.root = None
else:
return